Home » Php » php – Why can't I access the exploded array element immediately?

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

Posted by: admin July 12, 2020 Leave a comment


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.

How to&Answers:

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.


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


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 🙂