PHP 数组声明会导致意外的功能


php array declaration causes unintended functionality

$tally['zero']['status']='hello';
echo $tally['zero']['status'];
//prints hello, this is expected

在此示例中,为什么只打印第一个字母?

$tally = array( "zero" => '0');     
$tally['zero']['status']='hello';
echo $tally['zero']['status'];   
// prints h, I was expecting hello

在此示例中,为什么会引发错误?

$tally['zero'] = 0;
$tally['zero']['status']='hello';
echo $tally['zero']['status'];
//prints Warning: Cannot use a scalar value as an array

在此示例中,为什么只打印第一个字母?

$tally = array( "zero" => '0');
$tally['zero']['status'] = 'hello';
echo $tally['zero']['status']; // h

在 PHP 中,字符串可以像数组一样被索引,也可以就地修改。因此,在索引字符串时'status'变得0,并且hello的第一个字符分配给$tally['zero']的第一个字母。例如,这个:

$tally = array( "zero" => '01');
$tally['zero']['status'] = 'hello';
echo $tally['zero'];

将打印"h1"。

<小时 />

在此示例中,为什么会引发错误?

$tally['zero'] = 0;
$tally['zero']['status'] = 'hello';
echo $tally['zero']['status'];

就像错误所说,0不是一个数组。您无法为它编制索引,因此发出警告。

小心使用 " 和 '.而使用 " 内容可以解释为可变值。

0 != '0'   number/string

我认为所有的奥秘都隐藏在这里。