Home > Backend Development > PHP Problem > Is it possible to remove a certain value from a php array?

Is it possible to remove a certain value from a php array?

青灯夜游
Release: 2023-03-16 14:48:01
Original
2199 people have browsed it

php can remove a certain value in the array. Two removal methods: 1. Use unset() to delete after traversing through foreach, the syntax "foreach($arr as $k=>$v){if($v==="value"){unset($arr[ $k]);}}"; 2. Find the element through array_search() and delete it with unset(), the syntax is "unset($arr[array_search("value",$arr,true)])".

Is it possible to remove a certain value from a php array?

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

php can remove a certain item in the array value.

The following are two ways to remove specified values ​​​​from the array:

Method 1: Use unset to delete after traversing through foreach

  • Loop through the array through the foreach statement

  • In the loop body, use the "===" operator to compare the array elements, and if they are equal, use unset to delete them

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,2,3,4,"aa","bb");
var_dump($arr);
foreach($arr as $k=>$v){
	if($v==="aa"){
		unset($arr[$k]);
	}
}
var_dump($arr);
?>
Copy after login

Is it possible to remove a certain value from a php array?

Method 2: Find the element through array_search and delete it with unset

  • Use array_search searches the specified key value in the array and returns the corresponding key name

  • Use unset to delete the element based on the key name

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,2,3,4,"aa","bb");
var_dump($arr);
$key=array_search("bb",$arr,true);
unset($arr[$key]);
var_dump($arr);
?>
Copy after login

Is it possible to remove a certain value from a php array?

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Is it possible to remove a certain value from a php array?. 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