Home >Backend Development >PHP Problem >How to delete 0 values ​​from php array

How to delete 0 values ​​from php array

PHPz
PHPzOriginal
2023-04-19 11:38:22807browse

In PHP, array is a very commonly used data type that can store multiple values ​​and access these values ​​through indexes. Sometimes we need to delete specific values ​​from an array, this article will explore how to delete 0 values ​​from an array.

First, let's create an array containing 0 values ​​as an example:

$arr = array(1, 2, 3, 0, 4, 0, 5);

Next, we need to find an efficient way to remove 0 values ​​in PHP. There are two ways to accomplish this: using the array_filter() function and looping through the array.

Method 1: Use array_filter() Function

array_filter() The function is used to filter out elements that do not meet the conditions in the array and can be passed A callback function or use the default behavior, here we will use the callback function to filter the 0 value.

$new_arr = array_filter($arr, function ($value) {
    return $value !== 0;
});

This function will return a new array $new_arr, which does not contain elements with a value of 0.

Method 2: Loop through the array

We can also use a loop to traverse the array to delete elements with a value of 0. Here we use the foreach() function to achieve this. For elements whose value is 0, we can delete them from the array through the unset() function.

foreach ($arr as $key => $value) {
    if ($value === 0) {
        unset($arr[$key]);
    }
}

This method will modify the original array $arr and delete the 0 value in it.

Next, we can use the print_r() function to output the results of the two methods to verify whether they are valid:

// 使用 array_filter() 函数过滤 0 值
print_r($new_arr);

// 使用 foreach() 函数循环遍历数组删除 0 值
print_r($arr);

Run the above code, you will get the following Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 4
    [6] => 5
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 4
    [6] => 5
)

The results show that both methods can successfully delete the 0 value in the array.

Summary

In PHP, we can delete the 0 values ​​in the array through the array_filter() function or by looping through the array. The specific method to choose can be decided based on the usage scenario and personal habits. However, this can be done more simply and the code more readable using the array_filter() function.

The above is the detailed content of How to delete 0 values ​​from php array. 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