$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)])"."/> $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)])".">

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

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

青灯夜游
青灯夜游Original
2022-07-08 19:20:202164browse

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

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

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!

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