0

I have an array with multiple key.

Array 1

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

Output

Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

Expected Output

$age = array("value"=>"35", "value"=>"37", "value"=>"43");
Array ( [value] => 35 [value] => 37 [value] => 43 )
0

5 Answers 5

1

You can't

Indeed, array keys must be unique. Otherwise, what should the program output when you try to access value ?

But ...

If you need to store a list of value for one key, you can use array of arrays.

$array = array("value" => array());
array_push($array["value"], 35, 40, 53);
print_r($array)

And the output will be:

Array
(
    [value] => Array
        (
            [0] => 35
            [1] => 40
            [2] => 53
        )

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

Comments

1

Only way is to turn this array into 2D array:

$age = array(
    array("value" => "35"),
    array("value" => "37"),
    array("value" => "43")
);

-- Output --
Array
(
    [0] => Array
        (
            [value] => 35
        )

    [1] => Array
        (
            [value] => 37
        )

    [2] => Array
        (
            [value] => 43
        )

)

-- Usage -- 
$age[0]['value'];
$age[1]['value'];
$age[2]['value'];

But it completely depends if $age array is in our control and can be changed.

Comments

0

You can't

Array keys must be unique.

http://php.net/manual/en/language.types.array.php

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

3 Comments

yup i know. no way to get this output ?
No there is no way to get this output.
No idea why this is down voted, it's right, you cannot have identical array keys in the same level.
0

Yes, array key should be unique. So, whatever you are asking it's not possible. Can you tell us what's requirements? So that, people can suggest any alternate solution.

Comments

0

This cannot be possible with native php arrays. What you need is a multimap, and you can find several implementations of it on github. For example: link

EDIT: the link above is an interface. you need to include also link2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.