When I use the following code, it doesn't print out "else if test" until after I refresh the page.

unset($_SESSION["product"]);

if ( !empty($_SESSION["product"]) && ($_SESSION["product"] != NULL)) {
echo "if test";
} else if {
echo "else if test";
}

When I use:

var_dump($_SESSION["product"]);

It shows:

array(0) { }

(Added some code markup ~ Mod)

    A few things...

    • !empty($anything) will not be true if $anything is null, so there's no need for the separate NULL check.
    • Shouldn't that just be else {, not else if { since you don't have an if condition?

    Anyway, this works for me from the terminal:

    21:54 $ php -a
    Interactive shell
    
    php > $_SESSION = ['product' => 'something'];
    php > unset($_SESSION['product']);
    php > var_export($_SESSION);
    array (
    )
    php > if(!empty($_SESSION['product'])) {
    php {   echo "It's not empty";
    php { } else {
    php {   echo "It's empty.";
    php { }
    It's empty.
    

      When I paste $var_export($_SESSION); into my code, I get the following error:

      Notice: Undefined variable: var_export in C:\xampp\htdocs\TopView\cart.php on line 82

      Fatal error: Uncaught Error: Function name must be a string in C:\xampp\htdocs\TopView\cart.php:82 Stack trace: #0 {main} thrown in C:\xampp\htdocs\TopView\cart.php on line 82

        It's not $var_export (where are you pasting it from?), it's var_export.

          The code didn't actually make the call to unset the variables until after the not empty conditional was asked. I was misled because var_dump still printed out an empty session array. Once I changed the order of my code, it worked.

            Write a Reply...