Hi!
Trying to learn about arrays and i am wondering if any of you could help we show how to print out every other element from an array.
Example:
$array1 = array(1,2,3,4,5,6,7,8,9,10);
Would like to print out:
1,3,5,7,9
Hi!
Trying to learn about arrays and i am wondering if any of you could help we show how to print out every other element from an array.
Example:
$array1 = array(1,2,3,4,5,6,7,8,9,10);
Would like to print out:
1,3,5,7,9
You can use [man]array_filter[/man] for this. Theres even an example for that
Thanks a lot
O, just code it the old fashion way:
$array1 = array(1,2,3,4,5,6,7,8,9,10);
foreach ($array1 as $item) if (++$i&1) echo ($i>1?", ":"").$item;
or
for ($i = 0; $i < count($array1); $i += 2)
echo $array1[$i];
johanafm;10930404 wrote:or
for ($i = 0; $i < count($array1); $i += 2) echo $array1[$i];
Perhaps slightly more efficient (only executes count() once):
for($i = 0, $c = count($array1); $i < $c; $i += 2) {
echo $array1[$i];
}
Something that will work with any array (not just a sequentially enumerated array with a starting index of 0):
reset($array); // only needed if array pointer may have already been moved
while($value = current($array)) {
echo $value . "<br />\n";
next($array);
next($array);
}