Home  >  Article  >  Backend Development  >  How to delete elements from associative array in php

How to delete elements from associative array in php

藏色散人
藏色散人Original
2020-08-07 09:08:412439browse

How to implement deletion of elements in php associative array: first create a PHP sample file; then define a "removeArrayElement" method; then delete elements in the associative array through loop traversal.

How to delete elements from associative array in php

Recommended: "PHP Video Tutorial"

PHP associative array method to implement deletion of elements based on element value:

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

There is another method, which is more complicated than the above, but the effect is the same:

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

I hope this article will be helpful to everyone’s PHP programming design.

The above is the detailed content of How to delete elements from associative array in php. For more information, please follow other related articles on the PHP Chinese website!

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