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

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

问题描述

我怎样可以得到以下code的工作?


  

$ a =爆炸(S,$ STR)[0];


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


  

$ a =爆炸(S,$海峡); $ a = $ a [0];



解决方案

正如其他人所说,PHP是不同的JavaScript,因为它不能访问从函数返回数组元素。
第二种方法你列出的作品。你也可以抓住与电流()复位()或<$ C数组的第一个元素$ C> array_pop()像这样功能:

  $ a =电流(爆炸('S',$ STR)); //要么
$ A =复位(爆炸('S',$ STR)); //要么
$ A = array_pop(爆炸('S',$ STR));

如果您想删除爆炸可能会导致由于多次分离,可以通过其他参数之后传递两个设置其限制在2少量的开销。您也可以考虑使用str_pos和代替的strstr:

  $ a = SUBSTR($海峡,0,strpos($海峡,'S'));

所有这些选择都将正常工作。

修改的另一种方法是使用的list()(见的 PHP DOC )。有了它你可以抓住任何元素:

 列表($第一)=爆炸(S,$海峡); //第一
列表(,$秒)=爆炸(S,$海峡); //第二
列表(,, $三)=爆炸(S,$海峡); //第三
//等等。

这不是你的风格?你总是可以写一个小助手功能,以抓住从返回数组的功能元素:

 函数array_grab($改编,$键){返回($改编[$关键]); }$部分= array_grab(爆炸('S',$ STR),0); //使用方法:1元,等等。

编辑: PHP 5.4将支持数组语法,所以你能够做到:

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

How can I get the following code to work?

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

I only see solutions looking like this:

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

解决方案

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

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

EDIT: 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天全站免登陆