开发者

Why this fails in PHP?

echo explode(' ','开发者_StackOverflowA B')[0]

What's the right version?


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'));


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜