开发者

Why can't I access the exploded array element immediately?

Why can't 开发者_运维知识库I immediately access elements in the array returned by explode()?

For example, this doesn't work:

$username = explode('.',$thread_user)[1]; 
//Parse error: syntax error, unexpected '[

But this code does:

$username = explode('.',$thread_user); 
$username = $username[1];

I don't usually program in PHP, so this is rather confusing to me.


The reason it isn't obvious how to do what you want is that explode could return false. You should check the return value before indexing into it.


It's version dependent. PHP 5.4 does support accessing the returned array.

Source: http://php.net/manual/en/language.types.array.php#example-115


Actually, PHP simply does not support this syntax. In languages like Javascript (for instance), the parser can handle more complex nesting/chaining operations, but PHP is not one of those languages.


Since explode() returns an array, you may use other functions such as $username = current(explode('.',$thread_user));


I just use my own function:

function explodeAndReturnIndex($delimiter, $string, $index){
    $tempArray = explode($delimiter, $string);
    return $tempArray[$index];
}

the code for your example would then be:

$username = explodeAndReturnIndex('.', $thread_user, 1);


Here's how to get it down to one line:

$username = current(array_slice(explode('.',$thread_user), indx,1));

Where indx is the index you want from the exploded array. I'm new to php but I like saying exploded array :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜