How can I get the following code to work?
$a = explode(‘s’, $str)[0];
I only see solutions looking like this:
$a = explode(‘s’, $str); $a=$a[0];
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As others have said, PHP is unlike JavaScript in that it can’t access array elements from function returns.
The second method you listed works. You can also grab the first element of the array with the
current(),reset(), orarray_pop()functions like so:If you would like to remove the slight overhead that explode may cause due to multiple separations, you can set its limit to 2 by passing two after the other arguments. You may also consider using str_pos and strstr instead:
Any of these choices will work.
EDIT Another way would be to use
list()(see PHP doc). With it you can grab any element:That not your style? You can always write a small helper function to grab elements from functions that return arrays:
EDIT: PHP 5.4 will support array dereferencing, so you will be able to do: