0

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?

asked Jan 26, 2018 at 16:25
2
  • 3
    Change foreach ($argument as $innerArgument) to foreach ($argument as &$innerArgument). This way $innerArgument is a reference and not a copy. Commented Jan 26, 2018 at 16:28
  • Thanks! That was exactly what I needed, awesome! Commented Jan 26, 2018 at 16:31

1 Answer 1

2

There is a very simple way to do this.

You just have to change your foreach loop to reference your variables and not use a copy of your variables. You can do this with the ampersand symbol in front of your $innerArgument.

foreach ($argument as &$innerArgument) {
 $this->replaceEmptyObjectsWithNull($innerArgument);
} 

Notice the & symbol in front of $innerArgument in the loop.

You can learn more about this in the PHP docs. You can also learn more about references in general in the PHP docs.

answered Jan 26, 2018 at 16:31

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.