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
user4900638user4900638
1 Answer 1
array_walk_recursive() should do this perfectly easily
array_walk_recursive(
$myArray,
function (&$value) {
if (is_bool($value)) {
$value = 'I AM A BOOLEAN';
}
}
);
answered Jun 19, 2015 at 14:30
-
3The
&
(by reference) was what I'm looking for, thanks!Skoempie– Skoempie2017年11月01日 12:00:23 +00:00Commented Nov 1, 2017 at 12:00 -
1That's what I was looking forFosAvance– FosAvance2018年10月01日 06:45:16 +00:00Commented Oct 1, 2018 at 6:45
-
1thanks for answer,Is there any way can change value depending upon another key element's value of same arrayrahul singh– rahul singh2019年04月03日 11:03:29 +00:00Commented 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.2019年12月01日 21:43:29 +00:00Commented Dec 1, 2019 at 21:43
-
@rahulsingh yes you can. like this:
array_walk_recursive($myArray, function($value, $key){...});
Adam– Adam2023年03月17日 08:23:33 +00:00Commented Mar 17, 2023 at 8:23
lang-php