How to access array index when using explode() in the same line?

允我心安 提交于 2019-12-11 03:15:48

问题


Can't wrap my head around this...

Say, we explode the whole thing like so:

$extract = explode('tra-la-la', $big_sourse);

Then we want to get a value at index 1:

$finish = $extract[1];

My question is how to get it in one go, to speak so. Something similar to this:

$finish = explode('tra-la-la', $big_sourse)[1]; // does not work

Something like the following would work like a charm:

$finish = end(explode('tra-la-la', $big_sourse));

// or

$finish = array_shift(explode('tra-la-la', $big_sourse));

But what if the value is sitting somewhere in the middle?


回答1:


Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.




回答2:


Something like that :

end(array_slice(explode('tra-la-la', $big_sourse), 1, 1));

Though I don't think it's better/clearer/prettier than writing it on two lines.




回答3:


you can use list:

list($first_element) = explode(',', $source);

[1] would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)

list($first_element, $second_elment) = explode(',', $source);
// or
list(, $second_element) = explode(',', $source);



回答4:


My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:

$finish = end(explode('tra-la-la', $big_sourse, 3)); 

explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!



来源:https://stackoverflow.com/questions/3099598/how-to-access-array-index-when-using-explode-in-the-same-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!