Home >Backend Development >PHP Tutorial >Two ways to delete specific elements in an array in PHP_PHP Tutorial

Two ways to delete specific elements in an array in PHP_PHP Tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-21 15:01:12939browse

Method 1:

Copy code The code is as follows:

$arr1 = array( 1,3, 5,7,8);
$key = array_search(3, $arr1);

if ($key !== false)
array_splice($arr1, $key, 1);
var_dump($arr1);
?>


Output:
array(4) { [0]=> int(1) [1]=> int(5) [2]=> int(7) [3]=> int(8) }

Method 2:

Copy code The code is as follows:

$arr2 = array( 1,3, 5,7,8);
foreach ($arr2 as $key=>$value)
{
if ($value === 3)
unset($arr2 [$key]);
}
var_dump($arr2);
?>

Output:
array(4) { [0]=> int(1) [2]=> int(5) [3]=> int(7) [4]=> int(8) }


Summary: You can see that there is a difference between using array_splice() to delete specific values ​​and using unset to delete specific values.

If the array_splice() function is deleted, the index value of the array will also change.

If the unset() function is deleted, the index value of the array will not change.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328026.htmlTechArticleMethod 1: Copy the code as follows: ?php $arr1 = array(1,3, 5,7,8 ); $key = array_search(3, $arr1); if ($key !== false) array_splice($arr1, $key, 1); var_dump($arr1); ? Output: ...
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