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

How to delete a column element of an array in php

PHPz
PHPzOriginal
2023-04-26 10:25:25691browse

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

The output result is:

Array
(
    [0] => apple
    [2] => orange
)

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

The output result is :

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

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

    [2] => Array
        (
            [name] => Lucy
        )
)

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!

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