how to output only the last 4 items of array in a for loop?
hi all i got an array that has dynamic number of elements for example one time it has 10 items one time 20 items .But i am only intrested in last 4 items. how i can print those last 4 items inside for loop ?
PHP Code:
for($i = 0; $i < count($foo2[1]); $i++)
{
}
Re: how to output only the last 4 items of array in a for loop?
If you want to iterate through each element, then you could use the foreach.
Some examples:
PHP Code:
// Array
$arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
// 1. Using ForEach loop to print all the elements
echo '<br /> Using ForEach to print all the elements: <br />';
foreach($arr as $ele)
{
echo $ele . ' ';
}
// 2. Using For loop to print the last 4 elements
echo '<br /><br /> Using For loop to print the last 4 elements: <br />';
for($i = (count($arr)-4);$i<count($arr); $i++)
{
echo $arr[$i] . ' ';
}
// 3. Using array_slice() to slice the last 4 elements and then printing
echo '<br /><br /> Using array_slice() to slice the last 4 elements and then printing: <br />';
$temparr = array_slice($arr, -4, 4);
foreach($temparr as $ele)
{
echo $ele . ' ';
}
Reference:
:wave:
Re: how to output only the last 4 items of array in a for loop?
do you want output only last 4 items in looping? try this
PHP Code:
$total= count($foo2[1]);
for($i = $total-4; $i < count($foo2[1]); $i++)
{
echo $i;
}
Re: how to output only the last 4 items of array in a for loop?
In case the array contains less than four elements...
PHP Code:
$n = count($foo2[1]);
for ($i = max(0, $n - 4); $i < $n; ++$i)
{
//...
}