How to delete specified elements in an array in php?

coldplay.xixi
Release: 2023-03-03 09:14:02
Original
2843 people have browsed it

php method to delete specified elements in an array: 1. Use the [array_splice()] function to delete, the code is [$key = array_search(3, $arr1)]; 2. Use the [unset()] function Delete, the code is [unset($arr2[$key])].

How to delete specified elements in an array in php?

php method to delete specified elements in the array:

Method 1, use array_splice() to delete :

The code is 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);
?>
Copy after login

Output:

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

Method 2, use the unset() function to delete:

The code is as follows:

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

Output:

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

Summary:

You can see that using array_splice() to delete specific values ​​and using unset to delete specific values There is a difference.

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

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

Related learning recommendations: PHP programming from entry to proficiency

The above is the detailed content of How to delete specified elements in an array in php?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!