Reputation: 151
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
Reputation: 413
foreach ($test as $key => $arr) {
echo $test[$key]["name"];
}
OR
foreach ($test as $key => $arr) {
echo $arr["name"];
}
Upvotes: 1
Reputation: 891
Try this,
foreach ($test as $key => $arr) {
echo $arr["name"];
}
Upvotes: 0
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
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
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