Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php unset array from 2d session array

i am adding stuff to a 2d array like this:

 $_SESSION['vehicles'][] = array ('model' => $_REQUEST['blah1'], 'price' => $_REQUEST['blah2'], 'year' => $_REQUEST['blah3']);  

how would i remove all arrays from the session that have a 'model' = to a variable of my choice? (note: there will always be many arrays in the session with the same model.)

i have tried the below but it doesn't seem to remove anything from my session array:

$model = "toyota";
foreach ($_SESSION['vehicles'] as $vehicle) 
{
    unset($vehicle[$model]);
}

Thanks!

like image 660
toop Avatar asked Mar 17 '26 20:03

toop


2 Answers

$vehicle is passed by copy, so, unset $vehicle do nothing

$model = "toyota";
foreach ($_SESSION['vehicles'] as $idx => $vehicle){
    if($vehicle['model'] == $model){
        unset($_SESSION['vehicles'][$idx]);
    }
}
like image 125
Bil Avatar answered Mar 19 '26 11:03

Bil


$model = 'toyota';

// PHP <= 5.2
$_SESSION['vehicles'] = array_filter($_SESSION['vehicles'],
              create_function('$v', "return \$v['model'] != '$model';"));

// PHP 5.3+
$_SESSION['vehicles'] = array_filter($_SESSION['vehicles'],
              function ($v) use ($model) { return $v['model'] != $model; });

Or, your approach:

foreach ($_SESSION['vehicles'] as $key => $vehicle) {
    if ($vehicle['model'] == $model) {
        unset($_SESSION['vehicles'][$key]);
    }
}
like image 26
deceze Avatar answered Mar 19 '26 09:03

deceze