调用未定义的数组元素会显示另一个已定义元素的值
当调用数组的未定义元素时,它向我显示另一个已定义元素的值。
数组结构示例:
$array = array(
'a' => array(
'b' => 'c'
)
);
在 $array['a']['b']['x']
上使用 echo 命令时,它显示 'c'
的值。为什么会发生这种情况我真的不明白,因为 $array['a']['b']['x']
没有定义。
然后当我尝试使用命令 $array['a']['b']['x'] = 'y'; 添加另一个值时 它将 $array['a']['b']
的值重写为 'y'
不知何故,我真的不明白这种行为,有人可以解释一下吗这可能吗?然后我如何能够在 $array['a']['b']['x'] = 'xyz'
创建一个新的字符串值而不覆盖 $array ['a']['b']
?
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 value 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']
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它实际上与数组完全无关。这是一个字符串问题。
在 PHP 中,您可以访问并使用数组表示法修改字符串的字符。考虑这个字符串:
$a[0]
给出第一个字符 (f
),$a[1]
给出第二个字符,依此类推。以这种方式分配字符串将用新字符串的第一个字符替换现有字符,因此:
导致
$a
为'boo'
。现在您要做的就是传递一个字符
'x'
作为索引。 PHP 解析为索引0
(在字符串中传递一个数字,如'1'
),但会按预期工作(即访问第二个特点))。在您的情况下,字符串仅包含一个字符 (
c
)。因此调用$array['a']['b']['x'] = 'y';
与$array['a']['b'] 相同[0] = 'y';
只是将字符从c
更改为y
。如果您有更长的字符串,例如
'foo'
,则会产生$array['a']['b']['x'] = 'y';
$array['a']['b']
的值为'yoo'
。您无法在不覆盖$array['a']['b'] 的情况下为其分配新值。变量只能存储一个值。您可以做的是将一个数组分配给
$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[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:
results in
$a
being'boo'
.Now what you do is passing a character
'x'
as index. PHP resolves to the index0
(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 fromc
toy
.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:which will result in:
Further reading: