$value)" statement to traverse the array; 2. Use the "if($value==="specified value")" statement to determine whether the current array value needs to be removed. value, if yes, use the "unset($arr[$key])" statement to delete the element."/> $value)" statement to traverse the array; 2. Use the "if($value==="specified value")" statement to determine whether the current array value needs to be removed. value, if yes, use the "unset($arr[$key])" statement to delete the element.">

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

How to traverse a php array and remove specified values

青灯夜游
青灯夜游Original
2021-10-19 18:28:142023browse

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);
?>

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!

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