Remove Item From Session Array

I’m trying to remove an element for the session array $session[‘the_variable’] like this:

unset($session[‘the_variable’][$index]);

But it doesn’t work, any idea what i’m doing wrong ?

Thanks in advanced!

Edit: I see now that you have variable $session, not session itself. unset should do it, are you sure that you are trying to unset the right thing?

Yes, I’m sure, here is the whole code, and you’ll see that i’m trying with different methods.




$session = new CHttpSession;

$session->open();


$session = Yii::app()->session;

	

$_id = $_GET['_id'];

$_opt = $_GET['_opt'];

switch ($_opt) {


	case 'delete':


		$index = array_search($_id, $session['the_variable']);


		echo 'key: ' . $index . '<br/>';


		print_r(Yii::app()->session->get('the_variable'));


		echo '<br/>';




		// try to delete with all methods

		if (is_numeric($index)) {

			//print_r($session['the_variable']);


			foreach($_SESSION['the_variable'] as $k => $v) {

				if($v == $removeditem)

					unset($_SESSION['the_variable'][$k]);

			}			




			//Yii::app()->session->remove('the_variable')->$index; /* with this the whole array it's unset */


			unset($session['the_variable'][$index]);

			print_r($session['the_variable']);


			// $session['the_variable'] = array_diff($session['the_variable'], $index);


			echo 'OK <br/>';

		} else {

			echo 'not found';

		}

		

	break;

}






RESOLVED:


unset($_SESSION['the_variable'][$index]);

Now, why I must use the global variable $_SESSION and with the $session variable from Yii doesn’t work?

CHttpSession methods work on $_SESSION so both solution should working the same. To remove variable from session you can also use remove() method.

There is a good article about working with sessions: