tags:

views:

394

answers:

8

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
Note that the for() loop doesn't work on arrays with string indexes (obviously)
Pim Jager
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
+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
+1  A: 
foreach($array as $key => $value) echo $key, ' => ', $value;
Zed
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
A: 

Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.

shambleh
+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
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
A: 

Foreach before foreach: :)

reset($array); 
while(list($key,$value) = each($array))
{
  // we used this back in php3 :)
}
gnarf