1

I'm consuming an API which returns an array of objects as this:

$base = array(
    ["orange","_","banana"], 
    ["banana","_","_"], 
    ["_","apple","kiwi"], 
    ["_","raspberry","strawberry"]
);

And I intend to show "0" when key value is "_" however I haven't found a better way to do this than this:

foreach ($base as $key => $value) {
    for ($i=0; $i<=3;$i++) {
        if ($base[$key][$i]=="_")
            $base[$key][$i]="0";
    }
}

This works just fine since it's a simple demo but the real array is sometimes big and I've found this solution somewhat inefficient.

My question is, there's some php built-in function to do achieve this in or at least a better way to do this?

Thanks in advance guys,

1
  • 1
    That's not an associative array. That's an indexed arrays that contains other indexed arrays (multidimensional array). So when you say: when key value is "_", it doesn't really make sense, since all keys in your arrays are numeric. Commented Mar 24, 2020 at 9:50

2 Answers 2

2

Use array_walk_recursive(), pass the elements by reference and walk over the array, checking for the value _ - if its a match, replace it with 0.

$base = array(
    ["orange","_","banana"], 
    ["banana","_","_"], 
    ["_","apple","kiwi"], 
    ["_","raspberry","strawberry"]
);

array_walk_recursive($base, function(&$v) {
    if ($v === '_')
        $v = 0;
});

Output becomes

Array
(
    [0] => Array
        (
            [0] => orange
            [1] => 0
            [2] => banana
        )

    [1] => Array
        (
            [0] => banana
            [1] => 0
            [2] => 0
        )

    [2] => Array
        (
            [0] => 0
            [1] => apple
            [2] => kiwi
        )

    [3] => Array
        (
            [0] => 0
            [1] => raspberry
            [2] => strawberry
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

Holy smokes...array_walk_recursive where have you been all of my life! Neat and works like a charm! Thank you very much Qirel
2

You can replace _ with 0;

json_decode(str_replace('"_"','"0"',json_encode($base)));

2 Comments

This seemed like a great solution and made a lot of sense to me but didn't work :(
Your answer was correct, sorry. My mistake is that I didn't realized until now that I also needed a solution to replace not only "_" but "". Hence I had to use the other variant involving walk the array entirely. Thank you for you help Kris.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.