When we operate arrays, we often encounter the problem of needing to remove spaces in the array. PHP provides some functions for processing strings, including functions that can handle spaces in arrays. This article will introduce how to use PHP functions to remove spaces in an array.
A simple array:
$array = array(" apple ", "banana", " orange ", " pear ");
Our goal is to remove the spaces on both sides of each cell in the array and all empty cells. Use the following method to remove the spaces on both sides:
$array = array_map('trim', $array);
Here we use PHP's array_map() function, which can apply a function to each element of an array. Here, we apply the trim() function we defined to each element of the array to remove spaces in the array.
Next we need to remove empty cells. Using the following method, we can remove all spaces in the array, including empty cells:
$array = array_filter(array_map('trim',$array));
Here, we have used PHP’s array_filter() function. It filters each element in the array and returns a new array. After using the array_filter() function, all empty cells in the array will be filtered out.
To sum up, we can use PHP's array_map() function and array_filter() function to remove spaces in the array. The following is a complete code example:
$array = array(" apple ", "banana", " orange ", " pear "); $array = array_map('trim', $array); $array = array_filter(array_map('trim',$array)); print_r($array);
Output result:
Array ( [1] => banana [2] => orange [3] => pear )
We can see that the spaces on both sides are removed from the output result, and all empty cells are successfully filtered out . In actual development, this method can help us easily remove spaces in the array and improve our work efficiency.
The above is the detailed content of php function to remove spaces from array. For more information, please follow other related articles on the PHP Chinese website!