如何在数组的末尾删除一个元素,并在数组的开始添加一个元素


How to remove an element at the end and add an element at start in array PHP

好吧,这是我的头撞上了墙,但我不能弄清楚这个,我在PHP中创建最近的项目列表我也想在数组中添加一个元素开始并在数组中有5个元素后在末尾删除1但这不起作用

if(!isset($_SESSION['recent_items'])) {
    $_SESSION['recent_items'] = array();
}
if(isset($_SESSION['recent_items'])) {
    if(count($_SESSION['recent_items']) <= 4) {
        array_push($_SESSION['recent_items'], $script_id);
    } else {
        array_shift($_SESSION['recent_items']);
        array_unshift($_SESSION['recent_items'], $script_id);
    }
}

你需要的是array_pop而不是array_shift

if(!isset($_SESSION['recent_items'])) {
    $_SESSION['recent_items'] = array();
}
if(isset($_SESSION['recent_items'])) {
    if(count($_SESSION['recent_items']) <= 4) {
        array_push($_SESSION['recent_items'], $script_id);
    } else {
        array_pop($_SESSION['recent_items']);
        array_unshift($_SESSION['recent_items'], $script_id);
    }
}