Christian Page
Christian Page

Reputation: 151

PHP foreach not looping

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"];
}

Upvotes: 2

Views: 4023

Answers (7)

Rameshkrishnan S
Rameshkrishnan S

Reputation: 413

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

OR

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

Upvotes: 1

Andrey Volk
Andrey Volk

Reputation: 3549

Use

echo $arr["name"];

or

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

Upvotes: 0

Nikhil Mohan
Nikhil Mohan

Reputation: 891

Try this,

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

Upvotes: 0

Eineki
Eineki

Reputation: 14959

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

Upvotes: 0

Kevin Schmid
Kevin Schmid

Reputation: 771

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

Upvotes: 5

slashingweapon
slashingweapon

Reputation: 11317

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"];
}

Upvotes: 4

jtavares
jtavares

Reputation: 449

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]

Upvotes: 0

Related Questions