Calling PHP explode and access first element? [duplicate]

妖精的绣舞 提交于 2019-12-04 22:20:30

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.

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];

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.

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];

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

$a = explode("#", "1234#5678");
$last = $a[1];
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!