开发者

PHP - Using explode() function to assign values to an associative array

I'd like to explode a string, but have the resulting array have specific strings as keys rather than integers:

ie. if I had a string "Joe Bloggs", Id' like to explode it so that I had an associative array like:

$arr['first_name'] = "Joe";
$arr['last_name'] = "Bloggs";

at the moment, I can do:

$str = "Joe Bloggs";
$arr['first_name'] = explode(" ", $str)[0];
$arr['last_name'] = explode(" ", $str)[1];

which is inefficient, because I have to call explode twice.

Or I can do:

$str = "Joe Bloggs";
$arr = explode(" ", $str);
$arr['first_name'] = $arr[0];
$arr['last_na开发者_运维问答me'] = $arr[1];

but I wonder if there is any more direct method.

Many thanks.


I would use array_combine like so:

$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );

EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.


You can make use of list PHP Manual (Demo):

$str = "Joe Bloggs";
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);

$arr then is:

Array
(
    [last_name] => Bloggs
    [first_name] => Joe
)


You cannot do explode(" ", $str)[0] in PHP <= 5.3.

However, you can do this:

list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜