Home > Backend Development > PHP Problem > How to traverse a php array and remove specified values

How to traverse a php array and remove specified values

青灯夜游
Release: 2023-03-13 12:20:01
Original
2080 people have browsed it

Method: 1. Use the "foreach($arr as $key=>$value)" statement to traverse the array; 2. Use the "if($value==="specified value")" statement to determine the current Whether the array value is a value that needs to be removed, if so, use the "unset($arr[$key])" statement to delete the element.

How to traverse a php array and remove specified values

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php array traversal move Except the specified value

Implementation idea:

  • In PHP, if you want to traverse the array, you can use the foreach statement;

  • In the loop body, use the if statement and the "===" operator to determine whether the current array value is the specified value

    If so, use unset() The function can delete the element

Implementation code:

<?php
$arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
var_dump($arr);
foreach($arr as $key=>$value){
	if($value==="blue"){
		unset($arr[$key]);
	}
}
var_dump($arr);
?>
Copy after login

Output result:

How to traverse a php array and remove specified values

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to traverse a php array and remove specified values. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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