Jump to content

Advice/PHP Internal Function?? - Get last 20 associative array values?


Recommended Posts

I'm probably just rusty and can't recall but is there a way to mathematically get the last 20 values of a dynamically sized associative array? 

 

I realize I can remap the array with numeric indexes and then use that, I just wanted to make sure I'm not missing the easier (more efficient) way.

 

 

With the use of array_slice, the last 20 entries will be retained (including their indices.. so using an array with say 25 indices, the new array will start at index 5 and go through to 24:

 

$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
$last20 = array_slice($arr, -20, 20, true);
echo '<pre>'.print_r($last20, true); // index 5 thru 24, with values 6 thru 25

 

Not sure if this is a big deal or not.. but if you want to have the indices renamed from from 0 instead, you can use array_splice instead:

$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
$last20 = array_splice($arr, -20);
echo '<pre>'.print_r($last20, true); // index 0 thru 19, with values from 6 thru 25

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.