1

I am trying to combine two arrays. An associative one and a numeric array. $new_array = array_combine($array1, $array2). But it is taking the values from array one and setting them as the keys for the new array, which is what is meant meant to do.

But I need to use the keys of $array1 to be the keys of $new_array and the values of the $array2 to be the values of the $new_array. I also looked into merging the values of $array2 to $array1 but it does not work properly as the arrays don't share the same keys.

Here is an example.

$array1 = "fname" => "NULL", "lname" => "NULL", "id" => "NULL";

$array2 = "john", "smith", "11123";

$new_array = "fname" => "john" , "lname" => "smith", id => "11123";

I was thinking of using this array_combine(array_flip($array1), $array2);

But array_flip can't work with NULL;

2
  • 2
    array_flip() wouldn't give you the right result, perhaps you're looking for array_keys() Commented Oct 19, 2017 at 15:40
  • I am looking for other options - some mystery? Commented Oct 19, 2017 at 15:40

2 Answers 2

3

Use array_keys instead of array_flip like so:

$array1 = ["fname" => "NULL", "lname" => "NULL", "id" => "NULL"];

$array2 = ["john", "smith", "11123"];

$new_array = array_combine(array_keys($array1), $array2);

print_r($new_array);

Output:

Array
(
    [fname] => john
    [lname] => smith
    [id] => 11123
)

eval.in demo

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

Comments

1

You could simply iterate and assign

  $i = 0;
  foreach( $array1 as $key=>$value){
    $new_array[$key]=> $array2[$i];
    $i++;
  }

Comments

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.