Atiq Ahmad
Atiq Ahmad

Reputation: 39

how to unset a session variable?

I have the following code, but it does not work, I don't know what mistake I am committing due to which this code does not work:

Here is the code:

<?php session_start();
if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo']) && !empty($_GET['indexNo'])) 
{
   $indx = $_GET['indexNo'];
   foreach($_SESSION['itemsOrder'] as $key => $val)
{
 echo "$key => $val <br> " ;    
  if($indx == $val)
  {
    unset($_SESSION['itemsOrder'][$val]);

  }
  else
  {

    echo "indexNo was not unset <br>";
  }
 }
}
else 
{
    echo "indexNo not received!";
}
?>

Upvotes: 3

Views: 58

Answers (3)

Ankur Tiwari
Ankur Tiwari

Reputation: 2782

**Try This Code**
<?php session_start();
if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo'])) 
{
$indx = $_GET['indexNo'];
foreach($_SESSION['itemsOrder'] as $key => $val)
{
echo "$key => $val <br> " ; 
if($indx == $val)
{
    unset($_SESSION['itemsOrder'][$key]);

}
else
{

    echo "indexNo was not unset <br>";
}
}
}
else 
{
    echo "indexNo not received!";
}

Upvotes: 0

Iffi
Iffi

Reputation: 588

You need to unset the session array value than you must use its key instead of value. replaced:

unset($_SESSION['itemsOrder'][$val]); 

with:

unset($_SESSION['itemsOrder'][$key]);

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

Should be $key not the $val . Try with -

if($indx == $key)
{
    unset($_SESSION['itemsOrder'][$key]);

}

No need to use isset & empty together.

if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo']))

Upvotes: 2

Related Questions