开发者

PHP $_SESSION Array Problem

开发者 https://www.devze.com 2023-02-22 06:58 出处:网络
I am just trying to write a function in php that adds to the discount array but it doesn\'t seem to work at all.

I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.

    function addToDiscountArray($item){
        // if we already have the discount array set up
        if(isset($_SESSION["discountCalculator"])){

            // check that this item is not already in the array
            if(!(in_array($item,$_SESSION["discountCalculator"]))){
                // add it to the array if it isn't already present
                array_push($_SESSION["discountCalculato开发者_StackOverflow社区r"], $item);
            }
        }
        else{

            $array = array($item);
            // if the array hasn't been set up, initialise it and add $item
            $_SESSION["discountCalculator"] = $array;
        }
}

Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?

Many thanks


The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page. Try adding session_start() at the beginning of the function.

function addToDiscountArray($item) {
    if (!$_SESSION) { // $_SESSION is NULL if session is not started
        session_start(); // we need to start the session to populate it
    }
    // if we already have the discount array set up
    if(isset($_SESSION["discountCalculator"])){

        // check that this item is not already in the array
        if(!(in_array($item,$_SESSION["discountCalculator"]))){
            // add it to the array if it isn't already present
            array_push($_SESSION["discountCalculator"], $item);
        }
    }
    else{

        $array = array($item);
        // if the array hasn't been set up, initialise it and add $item
        $_SESSION["discountCalculator"] = $array;
    }
}

Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.

0

精彩评论

暂无评论...
验证码 换一张
取 消