-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 )

4
  • 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. Commented Oct 3, 2019 at 16:59
  • I need output like this Array ( [red] => blue [red] => yellow) Commented Oct 3, 2019 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: 3v4l.org/VTe7d Commented Oct 3, 2019 at 17:03
  • It's impossible, to create array, with two the same keys. Check thin in php manual. Commented Oct 3, 2019 at 19:16

1 Answer 1

-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"
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
"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?

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.