If I know the length of an array, how do I print each of its values in a loop?
+9
A:
$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}
Jonathan Sampson
2009-08-18 13:37:16
Note that the for() loop doesn't work on arrays with string indexes (obviously)
Pim Jager
2009-08-18 13:46:40
Count should be precalculated. In your example, it's being calculated on every loop. It should be:for ($i = 0, $count = count($array); $i < $count; $i++)
ryeguy
2009-08-18 13:48:36
+2
A:
Use a foreach loop, it loops through all the key=>value pairs:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
foreach($array as $value){
print $value."\n";
}
Pim Jager
2009-08-18 13:37:26
A:
If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.
Tom Ritter
2009-08-18 13:39:18
+1
A:
I also find that using <pre></pre>
tags around your var_dump or print_r results in a much more readable dump.
Jakub
2009-08-18 13:44:33
A:
either foreach:
foreach($array as $key => $value) {
// do something with $key and $value
}
or with for:
for($i = 0, $l = count($array); $i < $l; ++$i) {
// do something with $array[$i]
}
obviously you can only access the keys when using a foreach loop.
if you want to print the array (keys and) values just for debugging use var_dump
or print_r
knittl
2009-08-18 13:46:11
A:
Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}
gnarf
2009-08-18 14:39:17