Home > Backend Development > PHP Problem > How to delete a column element of an array in php

How to delete a column element of an array in php

PHPz
Release: 2023-04-26 13:47:45
Original
721 people have browsed it

In PHP, deleting a column element of an array is very simple. There are two main ways: using the unset() function and using the array_filter() function.

Method 1: Use the unset() function

The unset() function is used to destroy specified variables, including array elements. Therefore, we can use the unset() function to delete a column element of the array. For example, there is an array $fruit, which has 3 elements: "apple", "banana" and "orange". If you want to delete the second element (ie "banana"), you can write like this:

$fruit = array("apple", "banana", "orange");
unset($fruit[1]);
print_r($fruit);
Copy after login

The output result is:

Array
(
    [0] => apple
    [2] => orange
)
Copy after login

Method 2: Use the array_filter() function

array_filter() function can be used to filter the elements in the array. It will retain the elements whose callback function returns true. Next, remove the elements that return false. Therefore, we can delete a column element of the array by defining a callback function. For example, there is a two-dimensional array $data, in which each sub-array contains two elements: name and age. If you want to delete the age column, you can write like this:

$data = array(
    array("name" => "Tom", "age" => 20),
    array("name" => "Jack", "age" => 22),
    array("name" => "Lucy", "age" => 18)
);

function delete_age($item) {
    unset($item['age']);
    return $item;
}

$result = array_map('delete_age', $data);
print_r($result);
Copy after login

The output result is :

Array
(
    [0] => Array
        (
            [name] => Tom
        )

    [1] => Array
        (
            [name] => Jack
        )

    [2] => Array
        (
            [name] => Lucy
        )
)
Copy after login

Both of the above two methods can effectively delete elements in a column of the array. The specific method to choose can be decided according to actual needs.

The above is the detailed content of How to delete a column element of an array in php. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template