Calling PHP explode and access first element? [duplicate]
Asked Answered
L

5

26

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?

Luik answered 11/1, 2012 at 11:24 Comment(1)
You'll be able to do this (Array Dereferencing) in PHP 5.4, not in the current 5.3Spain
G
33

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.

Grapher answered 11/1, 2012 at 11:28 Comment(2)
and if you have many values in string then you can use $last = end(explode('#', $string));Superpower
Alternate for list is list(,$last) = ..... Then you won't have the first variable hanging when you don't need it.Ferretti
B
13

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];
Bhili answered 11/1, 2012 at 11:26 Comment(1)
Wow, that sucks :D ... ok, good I know now.Luik
O
8

Here's how to get it down to one line:

$last = current(array_slice(explode("#", "1234#5678"), indx,1));

Where indx is the index you want in the array, in your example it was 1.

Ovate answered 6/5, 2012 at 12:42 Comment(0)
S
5

You can't do this:

explode("#", "1234#5678")[1]

Because explode is a function, not an array. It returns an array, sure, but in PHP you can't treat the function as an array until it is set into an array.

This is how to do it:

 $last = explode('#', '1234#5678');
 $last = $last[1];
Shotgun answered 11/1, 2012 at 11:29 Comment(0)
N
3

PHP can be a little dim. You probably need to do this on two lines:

$a = explode("#", "1234#5678");
$last = $a[1];
Nape answered 11/1, 2012 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.