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

Why can't I access the elements in the array returned by explode() ?

For example, this does not work:

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

But this code does:

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

I usually do not program in PHP, so this is pretty confusing for me.

+7
arrays php explode
source share
6 answers

Actually, PHP simply does not support this syntax. In languages ​​such as Javascript (for example), the parser can handle more complex nesting / chaining operations, but PHP is not one of these languages.

+4
source share

The reason is not obvious how to do what you want explode to return false . You must check the return value before indexing it.

+6
source share

It depends on the version. PHP 5.4 supports access to the returned array.

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

+5
source share

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

+2
source share

I just use my own function:

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

The code for your example will be as follows:

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

Here's how to do it in one line:

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

Where indx is the index you want to get from the exploded array. I am new to php, but I like to say blasted array :)

+1
source share

All Articles