13

I'm trying to change the values of an array recursevely and all the examples that I've seen in stackoverflow don't fit for what I want so far.

Basically, I want to translate a boolean to String.

foreach($this->data as $key=>$value)
{
    if (is_bool($value))
    {
        $this->data[$key] = var_export($value, true);
    }       
}

This works just in the first level of the array. Also, I've tried to change the values with array_walk_recursive with no success as well.

Thanks in advance.

1 Answer 1

31

array_walk_recursive() should do this perfectly easily

array_walk_recursive(
    $myArray,
    function (&$value) {
        if (is_bool($value)) {
            $value = 'I AM A BOOLEAN';
        }
    }
);

Demo

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

5 Comments

The &(by reference) was what I'm looking for, thanks!
That's what I was looking for
thanks for answer,Is there any way can change value depending upon another key element's value of same array
@rahul not with this function. At most, you can find the visited leaf node (value) and its key (if you pass it into the callback), if you need access to a greater portion of data while recursively iterating, you will need to design your own custom function.
@rahulsingh yes you can. like this: array_walk_recursive($myArray, function($value, $key){...});

Your Answer

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