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

How to delete elements in an array in php

王林
王林Original
2020-08-03 11:51:392382browse

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);
?>

Output result:

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

(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);
?>

Output result:

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

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!

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