Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何修复PHP中未定义的偏移量错误_Php_Arrays - Fatal编程技术网

如何修复PHP中未定义的偏移量错误

如何修复PHP中未定义的偏移量错误,php,arrays,Php,Arrays,我有一个未定义的偏移量-此PHP代码中有一个错误: $testvar1 = false; $testvar2 = true; $testarray = [ "test1" => $testvar1, "test2" => $testvar2 ]; echo $testarray[0]; 注意:第9行的未定义偏移量:0 in/Path/to/ 那么如何修复呢?请注意这是一个关联数组,其中数组键是“测试1”和“测试2” 如果要打印第

我有一个
未定义的偏移量
-此
PHP代码中有一个错误

$testvar1 = false;
$testvar2 = true; 

$testarray = [
            "test1" => $testvar1,
            "test2" => $testvar2
];

echo $testarray[0];
注意:第9行的未定义偏移量:0 in/Path/to/


那么如何修复呢?

请注意这是一个关联数组,其中数组键是“测试1”和“测试2”

如果要打印第一个数组元素,可以编写:

echo $testarray['test1'];

如果要访问任何(索引或关联)数组的第一个元素_

您可以使用当前方法

为你的情况

echo current($testarray);

那里没有
0
索引。如果运行
print\r($testarray)
你会发现你只有
test1
test2
作为键…像这样访问它
$testarray['test1']。(注意,
var_dump($testarray['test1'])
最好在这种情况下查看内容)只是一个注意:在这种特定情况下,由于
echo false,因此页面中不会打印任何内容不显示任何内容。