Calling an undefined array element shows the value of another specific element

When the undefined array element is called, it shows me the value of another specific element.

An example of an array structure:

$array = array( 'a' => array( 'b' => 'c' ) ); 

When using the echo command on $array['a']['b']['x'] it shows me the value of 'c' . Why this happens, I really do not understand, since $array['a']['b']['x'] not defined.

And then when I try to add another value using the command $array['a']['b']['x'] = 'y'; It rewrites the value of $array['a']['b'] to 'y'

Somehow I really do not understand this behavior, can someone explain how this is possible? And how then can I create a new string value in $array['a']['b']['x'] = 'xyz' so as not to override $array['a']['b'] ?

+4
source share
1 answer

This does not really apply to arrays. This is a string problem.

In PHP, you can access and change the characters of a string with an array entry . Consider this string:

 $a = 'foo'; 

$a[0] gives you the first character ( f ), $a[1] second, etc.

Assigning a string in this way will replace the existing character with the first character of the new line, thus:

 $a[0] = 'b'; 

leads to $a 'boo' .

You are now passing the character 'x' as an index. PHP solves index 0 (passing a number in a string, such as '1' , will work as expected, though (for example, to access the second character)).

In your case, the string consists of only one character ( c ). Therefore, calling $array['a']['b']['x'] = 'y'; matches $array['a']['b'][0] = 'y'; which just changes the character from c to y .

If you had a longer string, for example 'foo' , $array['a']['b']['x'] = 'y'; , the value of $array['a']['b'] would be 'yoo' .


You cannot assign a new value to $array['a']['b'] without overwriting it. A variable can only store one value. What you can do is assign the array $array['a']['b'] and commit the previous value. For instance. You can do:

 $array['a']['b'] = array($array['a']['b'], 'x' => 'xyz'); 

which will result in:

 $array = array( 'a' => array( 'b' => array( 0 => 'c', 'x' => 'xyz' ) ) ); 

Further reading:

+5
source

All Articles