-1

Array_combine remove duplicate array

    <?php
        $a1=array("red","red");
        $a2=array("blue","yellow");
        print_r(array_combine($a1,$a2));
    ?>

This code give output : Array ( [red] => yellow )

But I want output like this: Array ( [red] => blue [red] => yellow )

theduck
  • 2,589
  • 13
  • 17
  • 23
  • 1
    And if you do `echo $arr['red'];` what do you expect it to output? Blue or yellow? You can't have two keys that is the same. – Andreas Oct 03 '19 at 16:59
  • I need output like this Array ( [red] => blue [red] => yellow) – Anuj Kumar Oct 03 '19 at 17:02
  • 2
    It's impossible. And that is not an echo. Answer what an echo should output. Your best option is to use a multidimensional array. See here: https://3v4l.org/VTe7d – Andreas Oct 03 '19 at 17:03
  • It's impossible, to create array, with two the same keys. Check thin in php manual. – yergo Oct 03 '19 at 19:16

1 Answers1

-1

The Andreas answer is correct. you can do this:

$a1 = ['red'];
$a2 = ['blue', 'yellow'];
$a3 = [];
foreach($a1 as $item1) {
  foreach($a2 as $item2) {
    $a3[$item1][] = $item2;
  }
}

print_r($a3);

The output:

array(1) {
  ["red"]=>
  array(2) {
    [0]=>
    string(4) "blue"
    [1]=>
    string(6) "yellow"
  }
}
  • And I think you have only this way. Do you know, Your codes never working. Because it can't have an array with several same keys. Have good time. – Hossein.Kiani Oct 03 '19 at 17:49
  • "your way" does not even have the same input as OP request. So yes, a downvote. Not the same input and not the same output. Is that useful? – Andreas Oct 03 '19 at 18:07