0

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.

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
TigerTiger
  • 10,590
  • 15
  • 57
  • 72

5 Answers5

2
while (count($_SESSION['myarray'] > 10)
{
    array_shift($_SESSION['myarray']);
}
Rik Heywood
  • 13,816
  • 9
  • 61
  • 81
1

You can use array_shift

if(count($_SESSION['myarray']) == 11))
    array_shift($_SESSION['myarray']);
Greg
  • 316,276
  • 54
  • 369
  • 333
1

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
  • 643,351
  • 109
  • 780
  • 844
0
if(count($_SESSION["myarray"]) == 10)
{
 $_SESSION["myarray"][9] = $var;
}
else
{
 $_SESSION["myarray"][] = $var
}

That should do.

usoban
  • 5,428
  • 28
  • 42
0
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
  • 11,485
  • 4
  • 42
  • 63