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

问题描述

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

I only see solutions looking like this:

解决方案

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爆炸,数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 02:18