Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling PHP explode and access first element? [duplicate]

Possible Duplicate:
PHP syntax for dereferencing function result

I have a string, which looks like 1234#5678. Now I am calling this:

$last = explode("#", "1234#5678")[1] 

Its not working, there is some syntax error...but where? What I expect is 5678 in $last. Is this not working in PHP?

like image 365
EOB Avatar asked Jan 11 '12 11:01

EOB


2 Answers

Array dereferencing is not possible in the current PHP versions (unfortunately). But you can use list [docs] to directly assign the array elements to variables:

list($first, $last) = explode("#", "1234#5678"); 

UPDATE

Since PHP 5.4 (released 01-Mar-2012) it supports array dereferencing.

like image 177
Felix Kling Avatar answered Oct 04 '22 04:10

Felix Kling


Most likely PHP is getting confused by the syntax. Just assign the result of explode to an array variable and then use index on it:

$arr = explode("#", "1234#5678"); $last = $arr[1]; 
like image 24
Aleks G Avatar answered Oct 04 '22 03:10

Aleks G