Sara Z Sara Z - 22 days ago 6
PHP Question

Printing also the duplicate in an array

I wonder why I don't get the 3 elements of my array.

$array1 = array(
"One" => 1,
"Two" => 2,
"One" => 1
);


When I print it:

echo 'array1:<pre>'; print_r($array1); echo '</pre>';


I get this:

array1:
Array
(
[One] => 1
[Two] => 2
)


This is not what I want. I need to show the following:

array1:
Array
(
[One] => 1
[Two] => 2
[One] => 1
)


Any help wil be appreciated.
Thanks in advance

Answer

Your array is a set of key/value pairs. Think of it as a dictionary:

array( "elephant" => "Big grey animal with tusks",
       "canary" => "Little Yellow Bird",
       "elephant" => "Candy that tastes like Skittles"
     )

When you print this one, you will always get the second definition of "elephant", just like in your code. Try changing the second "one" => 1 to "one" => 77.

Because PHP reads from top-down, the last one will always be the final answer, just like in variables.