|
-
Nov 17th, 2012, 03:23 PM
#1
Thread Starter
Frenzied Member
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++)
{
}
-
Nov 18th, 2012, 08:00 AM
#2
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:
If my post was helpful to you, then express your gratitude using Rate this Post. 
And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet
Social Group: VBForums - Developers from India
Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...
-
Dec 14th, 2012, 10:33 PM
#3
New Member
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;
}
-
Dec 17th, 2012, 10:51 PM
#4
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) { //... }
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|