Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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_name'] = $arr[1];

but I wonder if there is any more direct method.

Many thanks.

like image 800
Joe Avatar asked Jul 25 '11 10:07

Joe


2 Answers

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.

like image 75
Jon Gjengset Avatar answered Nov 03 '22 04:11

Jon Gjengset


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
)
like image 25
hakre Avatar answered Nov 03 '22 04:11

hakre