I'm trying to modify an array in a PHP 5 function.
Example input:
array('name' => 'somename', 'products' => stdClass::__set_state(array()))
Expected output:
array('name' => 'somename', 'products' => null)
I have written the following code to replace empty objects (which are stdClass::__set_state(array()) objects) with null. The method works fine (I've used some debug logs to check), but the array I'm giving it does not change.
private function replaceEmptyObjectsWithNull(&$argument){
if (is_array($argument)){
foreach ($argument as $innerArgument) {
$this->replaceEmptyObjectsWithNull($innerArgument);
}
} else if (is_object($argument)){
if (empty((array) $argument)) {
// If object is an empty object, make it null.
$argument = null;
\Log::debug("Changed an empty object to null"); // Is printed many times, as expected.
\Log::debug($argument); // Prints an empty line, as expected.
} else {
foreach ($argument as $innerArgument) {
$this->replaceEmptyObjectsWithNull($innerArgument);
}
}
}
}
I call this method like this:
$this->replaceEmptyObjectsWithNull($myArray);
\Log::debug($myArray); // myArray should be modified, but it's not.
What am I doing wrong here? I'm parsing the argument by reference, right?
foreach ($argument as $innerArgument)toforeach ($argument as &$innerArgument). This way$innerArgumentis a reference and not a copy.