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.
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.
Answer:
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.
Answer:
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
Answer:
Since explode() returns an array, you may use other functions such as $username = current(explode('.',$thread_user));
Answer:
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);
Answer:
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 🙂
Tags: phpphp