开发者

Calling an undefined array element is showing a value of another defined element

开发者 https://www.devze.com 2023-03-01 04:50 出处:网络
When calling an undefined element of an array, it is showing me a value of another defined element. Example of array structure:

When calling an undefined element of an array, it is showing me a value of another defined element.

Example of array structure:

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

When using echo command on $array['a']['b']['x'] it is showing me value of 'c'. Why this happens I really don't understand since $array['a']['b']['x'] is not defined.

And then when I try to add another value by using command $array['a']['b']['x'] = 'y'; It is rewriting the v开发者_如何学编程alue of $array['a']['b'] to 'y'

Somehow I really don't understand this behaviour, can someone explain how is that possible? And how then I will be able to create a new string value at $array['a']['b']['x'] = 'xyz' to not override $array['a']['b']?


It is actually not related to arrays at all. This is a string problem.

In PHP you can access and modify characters of a string with array notation. Consider this string:

$a = 'foo';

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

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

$a[0] = 'b';

results in $a being 'boo'.

Now what you do is passing a character 'x' as index. PHP resolves to the index 0 (passing a number in a string, like '1', would work as expected though (i.e. accessing the second character)).

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

If you had a longer string, like 'foo', $array['a']['b']['x'] = 'y'; would result in the value of $array['a']['b'] being '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 to assign an array to $array['a']['b'] and capture the previous value. E.g. you could 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:

  • Arrays
  • Strings
0

精彩评论

暂无评论...
验证码 换一张
取 消