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.

asked Jun 19, 2015 at 14:27

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

answered Jun 19, 2015 at 14:30
5
  • 3
    The &(by reference) was what I'm looking for, thanks! Commented Nov 1, 2017 at 12:00
  • 1
    That's what I was looking for Commented Oct 1, 2018 at 6:45
  • 1
    thanks for answer,Is there any way can change value depending upon another key element's value of same array Commented Apr 3, 2019 at 11:03
  • @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. Commented Dec 1, 2019 at 21:43
  • @rahulsingh yes you can. like this: array_walk_recursive($myArray, function($value, $key){...}); Commented Mar 17, 2023 at 8:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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