Kevin
Kevin

Reputation: 3150

Modify array recursively in PHP

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?

Upvotes: 0

Views: 88

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8620

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.

Upvotes: 2

Related Questions