PDA

View Full Version : FOREACH function for dummies


cinq
03-09-2005, 01:16 PM
Help jog this dummy's memory please :D


Array
(
[15] => Array
(
[0] => Array
(
[id] => 2
[name] => Tim
)

[1] => Array
(
[id] => 4
[name] => karl
)
}
[18] => Array
(
[0] => Array
(
[id] => 13
[name] => max
)

}
}


This is the array $guyscache
I want to find out the details of the first element of the main array ( [15] )
using a foreach statement, how would I do it ?



foreach ($guyscache AS $first)
{
foreach ($first AS $second)
{
$id=$second["id"];
$name=$second["name"];
echo $id.$name;
}
}


This basically will print out everyone on the list ( Tim, karl, max ).
However I only want (Tim and Karl printed).

How can I amend the above code ?
Thanks :)

Colin F
03-09-2005, 02:44 PM
foreach() will run through each option of the array (allthough I don't think it will go into subarrays...)

If you only want to fetch the data for tim and carl, you'd have to add an if{} statement to check if the arrays key is 15.

Or, in your example, just drop the first foreach and make the second into:

foreach($guyscache[15] AS $value) {}