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!
$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]);
}
}
$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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With