简体   繁体   中英

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

Ok so I am banging my head against the wall, but am not able to figure this out, am making recent items list in PHP where I want too add an element to start of an array and remove 1 at the end after I've 5 elements in the array but this is not working

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

What you need is array_pop and not 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM