Home >Backend Development >PHP Tutorial >PHP关联数组实现根据元素值删除元素的方法_PHP

PHP关联数组实现根据元素值删除元素的方法_PHP

WBOY
WBOYOriginal
2016-05-30 08:45:59790browse

本文实例讲述了PHP关联数组实现根据元素值删除元素的方法。分享给大家供大家参考。具体如下:

<&#63;php 
$array1 = array("a" => "green", "red", "blue", "red"); 
$array2 = array("b" => "green"); 
$result = array_diff($array1, $array2);
//这样就相当于删除$array1里的值为"green"的元素。 
print_r($result); 
&#63;>

还有一个方法,比上面的复杂一些,但是效果一样:

function removeArrayElement(&$ar,$val)
{
$tmp = array();
foreach($ar as $k => $arc)
{
  if($arc!=$val)
  {
  $tmp[$k]=$arc;
  }
}
$ar = $tmp;
unset($tmp);
}

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn