$v){loop body code}"; 2. In the loop body, use unset() to remove Specify the value, the syntax "if(is_array($v)){$ck=array_search(value,$v);if($ck){unset($arr[$k][$ck]);}}else{if ($v===value){unset($arr[$k]);}}"."/> $v){loop body code}"; 2. In the loop body, use unset() to remove Specify the value, the syntax "if(is_array($v)){$ck=array_search(value,$v);if($ck){unset($arr[$k][$ck]);}}else{if ($v===value){unset($arr[$k]);}}".">
Home >Backend Development >PHP Problem >How to remove a certain value from a two-dimensional array in php
Removal steps: 1. Loop through the outer array elements of the two-dimensional array, the syntax is "foreach($arr as $k=>$v){loop body code}"; 2. In the loop body , use unset() to remove the specified value, the syntax "if(is_array($v)){$ck=array_search(value,$v);if($ck){unset($arr[$k][$ck] );}}else{if($v===value){unset($arr[$k]);}}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the foreach statement and combine it The unset() function deletes a specified value in a two-dimensional array.
Implementation steps:
Step 1: Use the foreach statement to loop through the outer array elements of the two-dimensional array
foreach ($arr as $k => $v){ //循环体代码 }
Traverse the given $arr array, and in each loop, the value of the current array will be assigned to $v, and the key name will be assigned to $k.
Step 2: In the loop body, remove the specified value in the two-dimensional array
Use the is_array() function to determine whether the outer element is an array type (whether it is Subarray)
If so, use array_search() to get the key name corresponding to the specified value, and then use the unset() function to delete the element based on the key name
If not, directly use "===" to determine whether the current element is the specified element, and if so, use the unset() function to delete the element.
if (is_array($v)) { $ck = array_search(指定值, $v); if ($ck) { unset($arr[$k][$ck]); } } else { if ($v === 指定值) { unset($arr[$k]); } }
Complete implementation code: remove 1 in the two-dimensional array
<?php header("content-type:text/html;charset=utf-8"); $arr = array(1, 2, 3, array(4, 1, 6), array(7, 8, 9, 10)); echo "原数组:"; var_dump($arr); foreach ($arr as $k => $v) { if (is_array($v)) { $ck = array_search(1, $v); if ($ck) { unset($arr[$k][$ck]); } } else { if ($v === 1) { unset($arr[$k]); } } } echo "去除元素1后:"; var_dump($arr); ?>
Recommended study: " PHP video tutorial》
The above is the detailed content of How to remove a certain value from a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!