Home>Article>Backend Development> How to remove 0 values from php array
Two removal methods: 1. Use the array_diff() function to compare an array containing only "0" with the original array. The syntax is "array_diff($arr, [0])"; 2. Use the array_filter() function to call the callback function to filter the array, the syntax is "function f($var){return($var!==0);}$arr=array_filter($arr,"f");".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
Method 1: Use The array_diff() function removes 0
array_diff() function is used to compare the values of two (or more) arrays and return the difference.
array_diff(array1,array2,array3...);
Just use an array containing only "0" to compare with the original array, syntax:array_diff($arr, [0])
Example :
Note: The array_diff() function compares the values of two (or more) arrays (value in key=>value), and Returns a difference array containing all values that are in the compared array (array1) but not in any of the other argument arrays (array2 or array3, etc.).
Method 2: Use the array_filter() function to remove 0 in the array
The array_filter() function uses a callback function to filter the elements in the array.
This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.
array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
Parameters | Description |
---|---|
array | Required . Specifies the array to filter. |
callback | Optional. Specifies the callback function to be used. |
flag | Optional. Determine the parameter form received by the callback:
|
Example:
Note: If the array_filter() function does not have a callback function, the default is to delete the value in the array as false s project.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove 0 values from php array. For more information, please follow other related articles on the PHP Chinese website!