0

I have two numeric arrays (these arrays will always have the same number of keys and values).

$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array(value of the $array1 => $value of the array2);

If I write a while and fill the $array_final, it only fills with the last key and value

So it's like:

for ($i = 0; $i < count($array(1))
{
    $array_final = array($array1[$i] => $array2[$i]);
}
$array_final = array("key2" => "value2");

But I want:

$array_final = array("key1" => "value1", "key2" => "value2");
3
  • You mean you want to have 2 identical indexes in one array? No its impossible. Commented May 22, 2013 at 13:22
  • Look at array_combine Commented May 22, 2013 at 13:22
  • You are overwriting your array each time in the loop, look an Majid L solution. That's how to add the items. Commented May 22, 2013 at 13:27

3 Answers 3

1

You want array_combine

It does exatcly what you need

So basically

$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");

$array_final = array_combine($array1, $array2);
Sign up to request clarification or add additional context in comments.

Comments

1
for ($i=0; $i< sizeof($array1) &&  $i< sizeof($array2) ; $i++)
{
  $array_final[$array1[$i]] =$array2[$i];
}

1 Comment

Thx that's work fine but the method with array_combine takes less lines ;) !
0

You may try below code.


       $array1 = array(0 => "key1", 1 => "key2");
       $array2 = array(0 => "value1", 1 => "value2");
       $array_final = combine_if_same_keys($array1,$array2);
       print_r($array_final);


       function combine_if_same_keys( $array_one, $array_two ) {

         $expected = false;

          ksort($array_one);
          ksort($array_two);

         $diff = array_diff_key($array_one, $array_two);
         if( empty($diff) && count($array_one) == count($array_two) ) {
             $expected = array_combine( $array_one, $array_two );
         }

          return $expected;
       } 

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.