Home >Backend Development >PHP Problem >How to delete specified elements in php

How to delete specified elements in php

藏色散人
藏色散人Original
2020-07-03 09:22:252717browse

php method to delete specified elements: 1. Use "array_splice()" to delete the specified element, that is, a specific value, and the index value of the array changes; 2. Use the "unset" function to delete a specific value, but the array's index value changes. The index value has not changed.

How to delete specified elements in php

php method to delete specified elements

Method 1:

<?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 :

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

Method 2:

<?php
$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 using array_splice() to delete specific values ​​and using unset to delete specific values There is a difference in 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.

Recommended: "PHP Tutorial"

The above is the detailed content of How to delete specified elements in php. 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