调用 PHP 爆炸并访问第一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8818415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:34:31  来源:igfitidea点击:

Calling PHP explode and access first element?

phpstringexplode

提问by EOB

Possible Duplicate:
PHP syntax for dereferencing function result

可能的重复:
用于取消引用函数结果的 PHP 语法

I have a string, which looks like 1234#5678. Now I am calling this:

我有一个字符串,看起来像1234#5678。现在我称之为:

$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?

它不工作,有一些语法错误......但在哪里?我期望的是 5678 in $last. 这在 PHP 中不起作用吗?

回答by Felix Kling

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:

在当前的 PHP 版本中,数组解引用是不可能的(不幸的是)。但是您可以使用list[docs]将数组元素直接分配给变量:

list($first, $last) = explode("#", "1234#5678");

UPDATE

更新

Since PHP 5.4 (released 01-Mar-2012) it supports array dereferencing.

从 PHP 5.4(2012 年 3 月 1 日发布)开始,它支持数组解引用

回答by Aleks G

Most likely PHP is getting confused by the syntax. Just assign the result of explodeto an array variable and then use index on it:

PHP 很可能被语法弄糊涂了。只需将 的结果分配explode给一个数组变量,然后对其使用索引:

$arr = explode("#", "1234#5678");
$last = $arr[1];

回答by ragamufin

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

以下是如何将其归结为一行:

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

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

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

indx您想要在数组中的索引在哪里,在您的示例中它是 1。

回答by Alasdair

You can't do this:

你不能这样做:

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

Because explodeis 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.

因为explode是一个函数,而不是一个数组。当然,它返回一个数组,但在 PHP 中,您不能将函数视为数组,直到将其设置为数组。

This is how to do it:

这是如何做到的:

 $last = explode('#', '1234#5678');
 $last = $last[1];

回答by Rob Agar

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

PHP 可能有点暗。您可能需要在两行上执行此操作:

$a = explode("#", "1234#5678");
$last = $a[1];