Search code examples
phparray-push

how do I keep a certain number of elements in an array?


How do I keep a certain number of elements in an array?

function test($var)
{
    if(is_array($_SESSION['myarray']) {
        array_push($_SESSION['myarray'], $var);
    }
}

test("hello");

I just want to keep 10 elements in array $a. So when I call test($var) it should push this value to array but keep the number to 10 by removing some elements from top of the array.


Solution

  • I would do this:

    function test($var) {
        if (is_array($_SESSION['myarray']) {
            array_push($_SESSION['myarray'], $var);
            if (count($_SESSION['myarray']) > 10) {
                $_SESSION['myarray'] = array_slice($_SESSION['myarray'], -10);
            }
        }
    }
    

    If there a more than 10 values in the array after adding the new one, take just the last 10 values.