views:

160

answers:

3

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.

+4  A: 

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.

James McLeod
Thank you. I am not used to return values behaving like that and I missed that when I checked the PHP manual.
Mike Atlas
It's always seemed a little quirky to me, but it is useful, and no uglier than e.g. having to check calls to malloc in C for NULL returns.
James McLeod
It's actually just that the PHP syntax doesn't support this. You're simply saying it's intended that way to make people check their return values?
roe
No, not exactly. Rather, I think this is one of the most useful ramifications of the decision not to support this syntax.
James McLeod
James, you're absolutely right that for PHP to support this syntax would add another layer of complexity owing to the fact that in PHP, a soft-typed language, you cannot guarantee the return type of a function. However there are other cases where PHP's parser does in fact allow such conditions may occur. In these cases, PHP simply attempts the closest typecast it can manage and throws a warning message. Try accessing `$userID[1]` where $userID is an integer, for example.
Brian Lacy
+3  A: 

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.

Brian Lacy
^ the real answer. Even if you write a function that returns an invariant array, you still can't index the function call (as James' answer might lead you to believe), because it's simply a matter of the syntax not working.
Chuck
+1 for Chuck's comment - clearly some defensive programming has allowed me to avoid learning PHP as fully as I should. (and maybe I shouldn't try to answer questions on the last day of a three-day weekend...)
James McLeod
+1  A: 

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

qualbeen