为什么我不能立即访问由返回的数组中的元素explode()
?
例如,这不起作用:
$username = explode('.',$thread_user)[1];
//Parse error: syntax error, unexpected '[
但是这段代码确实:
$username = explode('.',$thread_user);
$username = $username[1];
我通常不使用 PHP 编程,所以这让我很困惑。
不清楚如何做你想做的事情的原因是它explode
可能会返回false
。您应该在索引返回值之前检查它。
它取决于版本。PHP 5.4确实支持访问返回的数组。
来源: http: //php.net/manual/en/language.types.array.php#example-115
实际上,PHP 根本不支持这种语法。在像 Javascript(例如)这样的语言中,解析器可以处理更复杂的嵌套/链接操作,但 PHP 不是这些语言之一。
由于explode() 返回一个数组,您可以使用其他函数,例如$username = current(explode('.',$thread_user));
我只是使用我自己的功能:
function explodeAndReturnIndex($delimiter, $string, $index){
$tempArray = explode($delimiter, $string);
return $tempArray[$index];
}
您的示例的代码将是:
$username = explodeAndReturnIndex('.', $thread_user, 1);
以下是如何将其简化为一行:
$username = current(array_slice(explode('.',$thread_user), indx,1));
indx
您想要从爆炸数组中获得的索引在哪里。我是 php 新手,但我喜欢说爆炸数组 :)