Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a way to explode an a string into an assoc array with keys from another array? example: i have an array

$array = array('firstname' => 'john', 'lastname' => 'smith');

now i have another piece of string like:

$fullname = 'Paul Phoenix';

so now i want to explode fullname into an array similar to $array with the same keys

$array2 = array('firstname' => 'paul', 'lastname' => 'phoenix');
share|improve this question

3 Answers 3

use like below

<?php
$a = array('firstname', 'lastname');

$fullname = 'Paul Phoenix';

$b = explode(" ",$fullname);

$c = array_combine($a, $b);

print_r($c);

?>

hope this will sure work for you.

share|improve this answer
    
Good answer and +1 for making it readable ;) –  Sébastien Oct 21 '13 at 12:03
$fullname = 'Paul Phoenix';

$name = array();
list($name['firstname'], $name['lastname']) = explode(' ', $fullname);

output:

array(2) {
  ["lastname"]=>
  string(7) "Phoenix"
  ["firstname"]=>
  string(4) "Paul"
}

Update:

$array = array('firstname' => 'john', 'lastname' => 'smith');
$fullname = 'Paul Phoenix';

$array2 = array_combine(array_keys($array), explode(' ', $fullname));

output:

array(2) {
  ["lastname"]=>
  string(7) "Phoenix"
  ["firstname"]=>
  string(4) "Paul"
}
share|improve this answer
    
you are hardcoding the keys of the array i need to take it from the 1st array itseld. if there is more keys in the 1st array there should be the exact same keys in the second array –  user2707590 Oct 21 '13 at 11:27
    
See updated answer –  JimL Oct 21 '13 at 11:29
    
great, thanks :) –  user2707590 Oct 21 '13 at 11:47

Use array_keys() to get the keys from $array, explode $fullname on the space, and then use array_combine() to combine the two:

$array2 = array_combine(array_keys($array), explode(' ', $fullname));
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.