Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing array values recursively in PHP

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.

like image 214
Ulysses Marins Avatar asked Jun 19 '15 14:06

Ulysses Marins


1 Answers

array_walk_recursive() should do this perfectly easily

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

Demo

like image 165
Mark Baker Avatar answered Oct 24 '22 07:10

Mark Baker