How to delete values from array in php

coldplay.xixi
Release: 2023-03-08 13:26:01
Original
2426 people have browsed it

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 thearray_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.

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

Output results:

Array ( [0] => a [1] => c )
Copy after login

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 usearray_diff().

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

3. array_diff_key () method

If you know the key of the array element you want to delete, you can usearray_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.

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

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!

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
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!