Home >Backend Development >PHP Problem >How to delete a certain field in PHP

How to delete a certain field in PHP

coldplay.xixi
coldplay.xixiOriginal
2020-08-15 14:29:563715browse

How to delete a field in a php array: 1. Use the function unset to delete the key of the array element value. The code is [unset($array[1])]; 2. Use the function [array_splice()] , the key of the array is re-indexed, the code is [array_splice($array,1].

How to delete a certain field in PHP

Method to delete a field in php array:

unset() method

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

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

Output results:

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

array_splice() method

If you Using 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.

Related learning recommendations:php programming(video)

The above is the detailed content of How to delete a certain field 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