您所在的位置:首页 / 知识分享

php非法字符串偏移

2023.04.06

260

ytj

php非法字符串偏移

你试图访问一个string就好像它是一个数组,有一个键-string. string不会明白的。在代码中,我们可以看到问题所在:"hello"["hello"];// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1"hello"[0];

// No errors.array("hello" => "val")["hello"];// No errors. This is *probably* what you wanted.纵深让我们看看这个错误:警告:非法字符串偏移“端口”在.。上面写着什么?上面说我们要用字符串'port'作为字符串的偏移量。就像这样:$a_string = "string";// This is ok:echo $a_string[0]; // secho $a_string[1]; // techo $a_string[2]; // r// ...

// !! Not good:echo $a_string['port'];// !! Warning: Illegal string offset 'port' in ...这是什么原因?因为某种原因你期望array,但你有一个string..只是搞混了。也许你的变量被改变了,也许它从来不是array,这真的不重要。我们能做些什么?如果我们知我们应该有一个array,我们应该做一些基本的调试,以确定为什么我们没有array..如果我们不知道我们会不会array或string事情变得更棘手了。我们能,会,可以做的是各种各样的检查,以确保我们没有通知,警告或错误的事情is_array和isset或array_key_exists:$a_string = "string";$an_array = array('port' => 'the_port');if (is_array($a_string) && isset($a_string['port'])) {

    // No problem, we'll never get here.

    echo $a_string['port'];}if (is_array($an_array) && isset($an_array['port'])) {

    // Ok!

    echo $an_array['port']; // the_port}if (is_array($an_array) && isset($an_array['unset_key'])) {

    // No problem again, we won't enter.

    echo $an_array['unset_key'];}// Similar, but with array_key_existsif (is_array($an_array) && array_key_exists('port', $an_array)) {

    // Ok!

    echo $an_array['port']; // the_port}有一些微妙的区别isset和array_key_exists..例如,如果$array['key']是null, isset回报false. array_key_exists会检查一下,好吧,钥匙存在.

相关新闻

PHP如何读取一个大文件txt

2018.12.06

2972

文件已经一次性全部被载入到内存中并将文件的每一行保存到了一个php数组中,一次性载入这个202MB的文件file函数用了0.67秒钟、file_get_contents函数用了0.25秒钟(看起来file_get_content要比file靠谱的多

商户+共享停车

2016.07.12

6126

随着城市发展,停车难已成为广大车主无法避免的痛点,这也进一步影响到车位资源紧缺商户的生意--因难停车而导致顾客流失或到访频次减少。