2

I just built a simple foreach loop to run through an array, but nothing is displaying. No php errors by the way.

Can someone tell me why this isn't working?

$test = array (
            "1" => array(
                "name"=>"something"
            ),
            "2" => array(
                "name"=>"something"
            )
        );

foreach ($test as $key => $arr) {
    echo $arr[$key]["name"];
}

7 Answers 7

5

Just use $arr["name"] instead of $arr[$key]["name"].

4

I think you meant...

foreach ($test as $key => $arr) {
    echo $test[$key]["name"];
}

Or, even more simply...

foreach ($test as $key => $arr) {
    echo $arr["name"];
}
3
  • 2
    $arr is just a convenient way to refer to $test[$key]. See php.net/manual/en/control-structures.foreach.php May 28, 2013 at 16:08
  • I edited the post to use $arr instead. You have a few ways to do this, obviously. May 28, 2013 at 16:08
  • I'm about to hit myself for making it more complicated. I'm not a noob when it comes to php, but I'm never looping through my own arrays, just the ones I pull back from a database.. May 28, 2013 at 16:11
1
foreach ($test as $key => $arr) {
    echo $test[$key]["name"];
}

OR

foreach ($test as $key => $arr) {
    echo $arr["name"];
}
0

Your array is written in a way that "1" and "2" are values and not keys.

what you need is:

$test = array (
        array(
            "name"=>"something"
        ),
        array(
            "name"=>"something"
        )
    );

also, you have a typo on your foreach. you need $test[$key] and not $arr[$key]

1
  • Ahhhhhhhh... (slams head down on desk) May 28, 2013 at 16:07
0

You should use the $key key in the array reference.

foreach ($test as $arr) {
   echo $arr["name"];
}

You can address the field of the array like

foreach ($test as $key=>$arr) {
    $test[$key][$name]
}

but doing so you do not use the direct reference to the inner arrays

0

Try this,

foreach ($test as $key => $arr) {
    echo $arr["name"];
}
0

Use

echo $arr["name"];

or

echo $test[$key]["name"];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.