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

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

Comments

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 Comments

$arr is just a convenient way to refer to $test[$key]. See php.net/manual/en/control-structures.foreach.php
I edited the post to use $arr instead. You have a few ways to do this, obviously.
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..
1
foreach ($test as $key => $arr) {
    echo $test[$key]["name"];
}

OR

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

Comments

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 Comment

Ahhhhhhhh... (slams head down on desk)
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

Comments

0

Try this,

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

Comments

0

Use

echo $arr["name"];

or

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

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.