PHP爆炸和数组索引 [英] PHP explode and array index

查看:27
本文介绍了PHP爆炸和数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让下面的代码工作?

How can I get the following code to work?

$a = expand('s', $str)[0];

$a = explode('s', $str)[0];

我只看到这样的解决方案:

I only see solutions looking like this:

$a = expand('s', $str);$a=$a[0];

$a = explode('s', $str); $a=$a[0];

推荐答案

正如其他人所说,PHP 与 JavaScript 不同,它无法从函数返回访问数组元素.您列出的第二种方法有效.您还可以使用 current()reset()array_pop() 函数获取数组的第一个元素,如下所示:

As others have said, PHP is unlike JavaScript in that it can't access array elements from function returns. The second method you listed works. You can also grab the first element of the array with the current(), reset(), or array_pop() functions like so:

$a = current( explode( 's', $str ) ); //or
$a = reset( explode( 's', $str ) ); //or
$a = array_pop ( explode( 's', $str ) );

如果您想消除因多次分离而导致爆炸可能导致的轻微开销,您可以通过在其他参数后传递两个来将其限制设置为 2.你也可以考虑使用 str_pos 和 strstr 来代替:

If you would like to remove the slight overhead that explode may cause due to multiple separations, you can set its limit to 2 by passing two after the other arguments. You may also consider using str_pos and strstr instead:

$a = substr( $str, 0, strpos( $str, 's' ) );

这些选择中的任何一个都可以.

Any of these choices will work.

EDIT 另一种方法是使用 list()(参见 PHP 文档).有了它,你可以抓取任何元素:

EDIT Another way would be to use list() (see PHP doc). With it you can grab any element:

list( $first ) = explode( 's', $str ); //First
list( ,$second ) = explode( 's', $str ); //Second
list( ,,$third ) = explode( 's', $str ); //Third
//etc.

那不是你的风格?你总是可以编写一个小的辅助函数来从返回数组的函数中获取元素:

That not your style? You can always write a small helper function to grab elements from functions that return arrays:

function array_grab( $arr, $key ) { return( $arr[$key] ); }

$part = array_grab( explode( 's', $str ), 0 ); //Usage: 1st element, etc.

PHP 5.4 将支持数组解引用,因此您可以:

PHP 5.4 will support array dereferencing, so you will be able to do:

$first_element = explode(',','A,B,C')[0];

这篇关于PHP爆炸和数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆