Home > Backend Development > PHP Tutorial > PHP associative array method to delete elements based on element value_PHP tutorial

PHP associative array method to delete elements based on element value_PHP tutorial

WBOY
Release: 2016-07-13 09:48:27
Original
945 people have browsed it

PHP associative array implements the method of deleting elements based on the element value

This article describes the example of PHP associative array implementing the method of deleting elements based on the element value. Share it with everyone for your reference. The details are as follows:

 ?

1

2

3

4

5

6

7

$array1 = array("a" => "green", "red", "blue", "red");

$array2 = array("b" => "green");

$result = array_diff($array1, $array2);

//这样就相当于删除$array1里的值为"green"的元素。

print_r($result);

?>

1

2

3

1

2

3

4

5

6

7

8

9

10

11

12

13

function removeArrayElement(&$ar,$val)

{

$tmp = array();

foreach($ar as $k => $arc)

{

if($arc!=$val)

{

$tmp[$k]=$arc;

}

}

$ar = $tmp;

unset($tmp);

}

4

5

6

$array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green"); $result = array_diff($array1, $array2); //This is equivalent to deleting the element with the value "green" in $array1. print_r($result);
?>
There is another method, which is more complicated than the above, but the effect is the same:  ?
1 2 3 4 5 6 7 8 9 10 11 12 13 removefunctionArrayElement(&$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. http://www.bkjia.com/PHPjc/1022669.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1022669.htmlTechArticlePHP associative array implements the method of deleting elements based on element value. This article describes the example of PHP associative array implementing deleting elements based on element value. method. Share it with everyone for your reference. The details are as follows...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template