'stay with the last 15 elements of an array [duplicate]

I have a database on couchdb, each document has a slightly complex structure, here is a small part:

   "category": {
      "1496805145": -1,
      "1497064141": -1,
      "1497150993": -1,
      "1497322542": -1,
      "1497487102": -1,
      "1497571701": -1,
      "1497657026": -1,
      "1497749178": -1,
      "1497920895": -1,
      "1498005644": -1,
      "1498091037": -1,
      "1498179039": -1,
      "1502183511": -1,
      "1502309289": -1,
      "1502395763": -1,
      "1502482211": -1,
      "1502568580": -1,
      "1502655044": -1,
      "1502741651": -1,
      "1502827775": -1,
      "1502914685": -1

I previously had more values, and this does not make sense, so I've made a code to limit it to a maximum of 15 values.

            $keys = array_keys((array)$pro["sources"][$id]);
            if(count($keys)>15)
            {
                $keys = asort($keys);
                foreach($keys as $key)
                {
                    if(count($keys) <= 15) break; 
                    else 
                    {
                        unset($pro["sources"][$id][$key]);
                        unset($keys[$key]);
                    }
                }
            }

my question is is there a php function that says "save me the last 15 elements of the arrray, but remove all the others"?

php


Solution 1:[1]

Use array_slice($a, -15, 15, true); where $a is the array.

-15 tells the function to start from 15 elements from the end.

15 tells the function to get 15 elements.

true tells the function to also preserve the keys, and I am assuming you do.

If you do not want to preserve the keys, you can use array_slice($a, -15); Since the third argument is missing, it will get the elements until the last is reached (so, 15)

Solution 2:[2]

I think you want array_slice(). You give it an offset and a length, and it will return those values as an array. See the PHP docs: http://php.net/manual/en/function.array-slice.php

an example of this:

$truncatedArray = array_slice($pro, -15);

This would give you the last 15 elements of the array $pro

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2