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

How to delete elements in an array in php

王林
Release: 2023-03-03 17:58:01
Original
2493 people have browsed it

How to delete elements in an array in php: You can use the unset() method to delete, such as [unset($array[1])]. Using the unset() method will not change other keys. If you want to reorder other keys, you can use the array_values() method.

How to delete elements in an array in php

#There are many ways to delete elements in an array. Here are some common ways.

(Recommended tutorial: php graphic tutorial)

If you want to delete an element in the array, you can use unset() or array_splice() method.

unset() method

Note: If you use the unset() method, it will not change other keys. If you want to change other To rearrange and sort by key, you can use array_values().

Code implementation:

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
unset($array[1]);
      //↑ 你要删除的数组元素值的键print_r($array);
?>
Copy after login

Output result:

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

(Video tutorial recommendation: php video tutorial)

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 replace the keys. Convert to numeric keys.

Code implementation:

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

Output result:

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

The above is the detailed content of How to delete 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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template