tags:

views:

87

answers:

3
echo explode(' ','A B')[0]

What's the right version?

+1  A: 

Try this,

$arr=explode(' ','A B');
echo($arr[0]);

You need to assign the value to an array before you can start accessing the items.

ILMV
I don't want to evolve another variable,because I'll echo it directly,but unfortunately fails.
You have no choice, you cannot access the returned array without assigning it to a variable.
ILMV
Don't let "i told ya php sucks" folks see this.
Amarghosh
Amarghosh, I told ya php sucks.
Michael Krelin - hacker
+3  A: 
list($var)=explode(' ','A B');

PHP doesn't allow access to the elements of the returned array. You can also try

echo array_shift( explode(' ','A B') );

IIRC, it works, but PHP complains about passing non-variable by reference.

And, of course, you can implement

function firstie($a) { return $a[0]; }
echo firstie(explode(' ','A B'));
Michael Krelin - hacker
+2  A: 
echo current(explode(' ', 'A B'));

or

$str = 'A B'; // assuming you're getting that string from somewhere
echo substr($str, 0, strpos($str, ' '));

I'd prefer the substr way, since you're dealing with strings anyway, not arrays.

deceze
+1, but current has the same problem like array_shift I mentioned.
Michael Krelin - hacker