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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With