5

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.

3 Answers 3

23

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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
)

1 Comment

Cheers for your answer and the demo.
7

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

However, you can do this:

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

1 Comment

Thanks for your answer and the warning re "explode(" ", $str)[0]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.