Home  >  Article  >  Backend Development  >  How to delete values ​​from array in php

How to delete values ​​from array in php

coldplay.xixi
coldplay.xixiOriginal
2021-03-05 17:24:032467browse

Methods to delete values ​​from array in php: 1. [array_splice()] method, code is [array_splice($array, 1, 1)]; 2. [array_diff()] method, code is [$ array = array_diff($array】.

How to delete values ​​from array in php

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, DELL G3 computer.

Methods for deleting values ​​from array in php:

1. array_splice() method

If you use the array_splice() method , the keys of the array will be automatically re-indexed, but it will not work for associative arrays. You need to use array_values() to convert the keys to numeric keys.

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
array_splice($array, 1, 1);
                   //↑ Offset which you want to delete
print_r($array);
?>

Output results:

Array
(
    [0] => a
    [1] => c
)

array_splice () has the same effect as the unset() function in releasing the specified elements of the array.

Delete multiple elements in the array

You cannot use it if you want to delete multiple elements in the array If you want to use the unset() or array_splice() function, you need to use the array_diff() or array_diff_key() method. To use this method, you need to know the key or value to be deleted.

2. array_diff() method

If you know the array element to be deleted, you can use array_diff().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff($array, ["a", "c"]);
                          //└────────┘→你要删除的元素
print_r($array );
?>
输出结果为:
Array
(
    [1] => b
)

3. array_diff_key () method

If you know the key of the array element you want to delete, you can use array_diff_key(). You need the key in the second parameter of the function Enter the key to be deleted in the value position. 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
)

Related video recommendations: PHP video tutorial

The above is the detailed content of How to delete values ​​from array 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