tags:

views:

62

answers:

6

Hi

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.

Thanks for your help.

A: 
if(count($_SESSION["myarray"]) == 10)
{
 $_SESSION["myarray"][9] = $var;
}
else
{
 $_SESSION["myarray"][] = $var
}

That should do.

usoban
+1  A: 

You can use array_shift

if(count($_SESSION['myarray']) == 11))
    array_shift($_SESSION['myarray']);
Greg
+2  A: 
while (count($_SESSION['myarray'] > 10)
{
    array_shift($_SESSION['myarray']);
}
rikh
A: 

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.

Gumbo
Thanks this is what I asked for. Cheers.
Wbdvlpr
A: 

You basically gave the answer yourself already with your tags.

You have these four functions which combined in the right way will do what you want:

  • array_pop — Pop the element off the end of array
  • array_push — Push one or more elements onto the end of array
  • array_shift — Shift an element off the beginning of array
  • array_unshift — Prepend one or more elements to the beginning of an array

All see here

tharkun
A: 
function array_10 (&$data, $value)
{
    if (!is_array($data)) {
        $data = array();
    }

    $count = array_push($data, $value);

    if ($count > 10) {
        array_shift($data);
    }
}

Usage:

$data = array();

for ($i = 1; $i <= 15; $i++) {
    array_10($data, $i);
    print_r($data);
}
Anti Veeranna