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 :
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,0,1,"a","b","c",0,"d","a","c"); echo "原数组:"; var_dump($arr); $arr = array_diff($arr, [0]); echo "去除0后:"; var_dump($arr); ?>
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:
<?php header('content-type:text/html;charset=utf-8'); function f($var) { return($var!==0); } $arr=array(1,2,3,0,1,"a","","c",0); echo "原数组:"; var_dump($arr); $arr = array_filter($arr,"f"); echo "去除0后:"; var_dump($arr); ?>
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.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,0,1,"0","","c",0,null,FALSE); echo "原数组:"; var_dump($arr); $arr = array_filter($arr); var_dump($arr); ?>
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!