Home>Article>Backend Development> How to remove elements with value equal to 3 from php array
Implementation steps: 1. Customize a filter function to process arrays and return array elements whose value is not equal to 3. The syntax is "function function name ($num) {return ($num!=3)" ;}"; 2. Use the array_filter() function to call a custom filter function to process the specified array, "array_filter($arr,"function name")".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use array_filter The () function filters the array and removes elements with a value equal to 3, that is, retains elements with a value not equal to 3.
array_filter() function uses a callback function to filter 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.
Implementation method:Just set the condition in the callback function called by the array_filter() function, and return the array element whose value is not equal to 3.
Description:
array_filter - Use the callback function to filter the elements of the array
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters:
◇array: the array to be traversed
◇callback: the callback function used
If the callback callback function is not provided, all "empty" elements of the array in the array will be deleted. See empty() for how PHP determines "empty" elements.
◇Mode determines which parameters are sent to the callback flag:
ARRAY_FILTER_USE_KEY - Use the key name as the only parameter of the callback callback, not the value
ARRAY_FILTER_USE_BOTH - Pass both the value and the key as arguments to the callback instead of just passing the value
The default value is 0, passing only the value as the callback The only parameter.
Return value: Returns the filtered array.
array_filter iterates through each value in the array array and passes each value to the callback callback function. If the callback function returns true, the current value in array is returned to the result array.
The key names (subscripts) of the returned result array array will remain unchanged. If the array parameter is an index array, the returned result array key names (subscripts) may be discontinuous. Arrays can be reindexed using the array_values() function.
When the array_filter() function is used to declare a callback function, it will delete false values (null values), but if the callback function is not specified, all elements in the array with a value equal to FALSE, such as null, will be deleted String or NULL value.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove elements with value equal to 3 from php array. For more information, please follow other related articles on the PHP Chinese website!