如何在数组中保留一定数量的元素?

时间:2022-01-11 21:26:22

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.

我只想在数组$ a中保留10个元素。因此,当我调用test($ var)时,它应该将此值推送到数组,但是通过从数组顶部删除一些元素将数字保持为10。

5 个解决方案

#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.

如果在添加新值后数组中的值超过10个,则只取最后10个值。

#2


while (count($_SESSION['myarray'] > 10)
{
    array_shift($_SESSION['myarray']);
}

#3


You can use array_shift

你可以使用array_shift

if(count($_SESSION['myarray']) == 11))
    array_shift($_SESSION['myarray']);

#4


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

That should do.

那应该做。

#5


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);
}

#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.

如果在添加新值后数组中的值超过10个,则只取最后10个值。

#2


while (count($_SESSION['myarray'] > 10)
{
    array_shift($_SESSION['myarray']);
}

#3


You can use array_shift

你可以使用array_shift

if(count($_SESSION['myarray']) == 11))
    array_shift($_SESSION['myarray']);

#4


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

That should do.

那应该做。

#5


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);
}