Results 1 to 4 of 4

Thread: how to output only the last 4 items of array in a for loop?

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Apr 2005
    Posts
    1,907

    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++)
    {




  2. #2
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    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, -44);
    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,...

  3. #3
    New Member
    Join Date
    Dec 2012
    Posts
    11

    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;



  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    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
  •  



Click Here to Expand Forum to Full Width