Home >Backend Development >PHP Problem >How to remove 0 values from php array (three methods)
In PHP development, we often need to process arrays. Sometimes, we may need to remove 0 values from an array. In this case, we can use some built-in PHP functions to remove the 0 values.
PHP provides multiple functions to remove 0 values from arrays, such as array_filter, array_diff and array_unique. The following describes how to use these functions.
1. Array_filter function:
The array_filter function in PHP can remove empty values, false, 0 and null from the array, while leaving other values unchanged. The function is used as follows:
$nums = [1, 0, '2', false, '', 3, null, 4]; $result = array_filter($nums); print_r($result);
The array $nums contains multiple types of values, including numbers, strings, Boolean values, and null. We can use the array_filter function to process it and remove all empty values, false, 0, and null values. Remove from array. The result in the above code will be:
Array ( [0] => 1 [2] => 2 [5] => 3 [7] => 4 )
2. array_diff function:
The array_diff function in PHP can compare one array with another array and return the difference. We can compare an array containing only 0 with the original array, and the returned result is an array with all 0 values removed. The function is used as follows:
$nums = [1, 0, 2, 0, 3, 0, 4]; $zeros = [0]; $result = array_diff($nums, $zeros); print_r($result);
In the above code, we first define an array containing A $nums array of multiple elements, which contains multiple 0 values, then defines a $zeros array containing only one 0 value, compares the $nums array with the $zeros array, returns the difference, and finally gets a Array of all 0 values. The result of the above code will be:
array ( 0 => 1, 2 => 2, 4 => 3, 6 => 4, )
3. array_unique function:
The array_unique function in PHP can remove duplicate elements from the array. We can first remove all 0 values in the array. , and then remove duplicate elements. The method of using the function is as follows:
$nums = [1, 0, 2, 0, 3, 0, 4, 3]; $result = array_unique(array_filter($nums, function($value) { return $value !== 0; })); print_r($result);
In the above code, we first use the array_filter function to remove all 0 values in the array, and then use the array_unique function to remove duplicate elements from the array after removing the 0 values. The result of the above code will be:
array ( 0 => 1, 2 => 2, 4 => 3, 6 => 4, )
The above are the three methods of removing 0 values in arrays in PHP. Readers can choose the appropriate method to use according to actual needs.
The above is the detailed content of How to remove 0 values from php array (three methods). For more information, please follow other related articles on the PHP Chinese website!