I am trying to iterate over a php object and changing each string value by reference, but something is just not working. In some arrays the strings will not be changed. Anyone has an idea why? Or has a suggestion on how to solve the task?
Here is my code:
recursive_object_string_changer($object);
function recursive_object_string_changer($object)
{
if($object == null) {
return;
}
foreach ($object as &$attribute) {
if (is_string($attribute)) {
$attribute = $attribute."!";
} else if (is_array($attribute)) {
recursive_object_string_changer($attribute);
} else if (is_object($attribute)) {
recursive_object_string_changer($attribute);
}
}
unset($attribute);
}
Thank you very much!
CodePudding user response:
I think you want to make the function's signature also accept the initial object as a reference so that the recursion works on subsequent calls.
recursive_object_string_changer($object);
function recursive_object_string_changer(&$object)
{
if ($object === null) {
return;
}
foreach ($object as &$attribute) {
if (is_string($attribute)) {
$attribute .= "!";
} elseif (is_array($attribute)) {
recursive_object_string_changer($attribute);
} elseif (is_object($attribute)) {
recursive_object_string_changer($attribute);
}
}
unset($attribute);
}
I used this for a sample:
$object = new stdClass();
$object->string = 'Test';
$object->array = [
'a',
'b',
'c',
];
$subObject = new stdClass();
$subObject->string = 'Another String';
$object->object = $subObject;
Which produces:
object(stdClass)#1 (3) {
["string"]=>
string(5) "Test!"
["array"]=>
array(3) {
[0]=>
string(2) "a!"
[1]=>
string(2) "b!"
[2]=>
string(2) "c!"
}
["object"]=>
object(stdClass)#2 (1) {
["string"]=>
string(15) "Another String!"
}
}
You might always want to add a guard before the for
loop to make sure that $object
is an array or an object in the first place.