开发者

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;
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜