Reputation: 17
In the foreach
I want to access the array value and the array looks like this.
Array
(
['name'] => John Doe
['age'] => 25
['from'] => Australia
)
How do I get the value of name
age
and from
?
With echo $item['name']
and return Undefined index: name
.
Upvotes: 1
Views: 196
Reputation: 41478
If you are foreaching over that array you just want ot echo the item:
$the_array = array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz');
foreach($the_array as $item){
//the first iterations will echo out $the_array['name'],
//second $the_array['age'], etc...
echo $item;
//in this loop $item['name'] has no meaning if that's what you're doing....
}
Now if it's really an array of arrays you can do this
$the_array = array(array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz'));
foreach($the_array as $item){
foreach($item as $key=>$value){
echo $key." ".$value;
}
}
If you're not positive the values you want to echo are being set but dont want the inner loop you might:
foreach($the_array as $item){
$name =isset($item['name']) ?$item['name'] : null;
echo $name;
$age =isset($item['age']) ?$item['age'] : null;
echo $age;
//...etc...
}
Upvotes: 2