user1692333
user1692333

Reputation: 2597

How to set array key to null if it does not exist?

For example i have an array:

array(
    'a' => 'value',
    'b' => 'value',
    'c',
    'd' => 'value',
    'e' => array(
        'f' => 'value',
        'g',
        array(
            'h' => 'value',
            'i'
        )
    ),
    'k',
    'l' => 'value'
);

I need recursively walk trough it and set key to NULL if it doesn't exists like this:

array(
    'a' => 'value',
    'b' => 'value',
    NULL => 'c',
    'd' => 'value',
    'e' => array(
        'f' => 'value',
        NULL => 'g',
        array(
            'h' => 'value',
            NULL => 'i'
        )
    ),
    NULL => 'k',
    'l' => 'value'
);

UPDATE I need this because i need to encode array in JSON and push to browser. The problem is that the json_encode sets key to 0 if it not exists, but if there is NULL it also remains the same in browser. So when i using this array in JS, i can detect where is the real 0 and where 0 was created because there was no key.

Upvotes: 0

Views: 2416

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

The keys do exist, they are just automatically assigned and are numeric. From Arrays

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

You cannot detect, if the numeric key was assigned explicitly or if the key was just omitted. You can do this only at the time when the array is created or the value is appended to the array. Afterwards, you can only replace numeric keys with some other value.

Additionally

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

This means, you cannot replace missing keys with NULL, but only one of them. If you set multiple keys to NULL, every assignment will delete the previous NULL key/value pair.

And finally

Additionally the following key casts will occur:

  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".

Upvotes: 2

bwoebi
bwoebi

Reputation: 23787

Use array_walk_recursive.

array_walk_recursive($array, function (&$value, &$key) {
    $value = NULL; /* for example as you cannot use multiple NULL-keys nor set the key to NULL... */
});

P.s.: For an explanation why you cannot use NULL-keys, see the post of @OlafDietsche

Upvotes: 0

Related Questions