1

I am new to php, I have an associative array like this

$arr['Joe'] = "test1";
$arr['Joe'] = "test2";
$arr['Joe'] = "test3";

how do I loop through all the values test1, test2, test3 of this specific key Joe?

I tried this

foreach ($arr as $key => $value) {
    echo $value;
}

and this

foreach ($arr as $key => $value) {
    echo $arr [$key]['Joe'];
}

But nothing ! Please help me?

4
  • 5
    You can't have multiple keys with the same name. In your case Joe will always be test3. Commented Aug 3, 2015 at 15:01
  • oh! I didn't know that, is there any other ways to hold multiple values in an associative array? Commented Aug 3, 2015 at 15:05
  • Yes. arrays of arrays. Commented Aug 3, 2015 at 15:09
  • you are setting the values wrong to the array, do this instead $arr['Joe'][0] = "test1"; etc.. Commented Aug 3, 2015 at 15:09

2 Answers 2

4

I think this is what you want:

<?php

$arr['Joe'][] = "test1";
$arr['Joe'][] = "test2";
$arr['Joe'][] = "test3";

foreach ($arr['Joe'] as $key => $value) {
    echo $value;
}
?>

By adding [] after ['Joe'] the values will be saved like this:

(
    [Joe] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
        )

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

Comments

0

To hold multiple values in an associative array they each need to be unique. eg.

$arr['Joe1'] = "test1";
$arr['Joe2'] = "test2";
$arr['Joe3'] = "test3";

and then

foreach ($arr as $value) {
    echo $value;
}

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.