Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 453
Mike Atlas Avatar asked Feb 15 '10 21:02

Mike Atlas


1 Answers

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.

like image 102
James McLeod Avatar answered Sep 22 '22 02:09

James McLeod