Home > Backend Development > PHP Problem > How to delete multiple elements from an array in php

How to delete multiple elements from an array in php

藏色散人
Release: 2023-03-11 07:36:01
Original
1902 people have browsed it

php method to delete multiple elements of an array: 1. Use the array_diff() function to delete multiple elements of the array; 2. Use the array_diff_key() function to delete multiple elements of the array.

How to delete multiple elements from an array in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How to delete multiple elements of an array in php?

Delete multiple elements in the array

If you want to delete multiple elements in the array, you cannot use the unset() or array_splice() function. , you need to use the array_diff() or array_diff_key() method, which requires knowing the key or value to be deleted.

array_diff() method

If you know the array element you want to delete, you can use array_diff().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff($array, ["a", "c"]);
                          //└────────┘→你要删除的元素
print_r($array );
?>
Copy after login

The output result is:

Array
(
    [1] => b
)
Copy after login

array_diff_key() method

If you know the key of the array element to be deleted , you can use array_diff_key(). You need to enter the key to be deleted in the key value position of the second parameter of the function. The value is not required and can be optional.

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                               //↑           ↑ 你要删除的数组键
print_r($array);
?>
输出结果为:
Array (
    [1] => b
)
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete multiple elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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