why I cannot unset the value of an array(PHP)
I want to unset a field of a two-dimensional array. I got a function like this, but it doesn't work:
function excludeOldSc开发者_如何学编程reeningDate($array){
foreach($array as $val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}
Because you're unsetting only temporary variable $val
function excludeOldScreeningDate($array){
foreach($array as $index => $val){
if($val['ref'] == 'G'){
unset($array[$index]['screening_date']);
}
}
return $array;
You should pass elements of an array by reference:
function excludeOldScreeningDate($array){
foreach($array as &$val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}
Notice the foreach($array as &$val){
line has changed.
If you want to edit the values in the array, you can read each array element by reference. Put a &
in front of $val
in the foreach
.
function excludeOldScreeningDate($array){
foreach($array as &$val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}
精彩评论