Reputation: 2011
If I know the length of an array, how do I print each of its values in a loop?
Upvotes: 51
Views: 326913
Reputation: 12758
Another advanced method is called an ArrayIterator
. It’s part of a wider class
that exposes many accessible variables
and functions
. You are more likely to see this as part of PHP
classes and heavily object-oriented
projects.
$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];
$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();
while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}
Upvotes: 1
Reputation: 1907
for using both things variables value and kye
foreach($array as $key=>$value){
print "$key holds $value\n";
}
for using variables value only
foreach($array as $value){
print $value."\n";
}
if you want to do something repeatedly until equal the length of array us this
// for loop
for($i = 0; $i < count($array); $i++) {
// do something with $array[$i]
}
Thanks!
Upvotes: 11
Reputation: 361
Here is example:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}
Upvotes: 5
Reputation: 268512
$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}
Upvotes: 129
Reputation: 106412
Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}
Upvotes: 0
Reputation: 265966
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
Upvotes: 2
Reputation: 20473
I also find that using <pre></pre>
tags around your var_dump or print_r results in a much more readable dump.
Upvotes: 4
Reputation: 3843
Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.
Upvotes: 0
Reputation: 101400
If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.
Upvotes: 0
Reputation: 32129
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";
}
Upvotes: 14