Home>Article>Backend Development> How to remove 0 values from php array

How to remove 0 values from php array

青灯夜游
青灯夜游 Original
2022-10-10 18:27:27 2526browse

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

How to remove 0 values ​​from php array

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 :

How to remove 0 values ​​from php array

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:

  • ARRAY_FILTER_USE_KEY - callback accepts the key name as the only parameter
  • ARRAY_FILTER_USE_BOTH - callback accepts both key name and key value

Example:

How to remove 0 values ​​from php array

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.

How to remove 0 values ​​from php array

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!

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