php function to remove spaces from array

王林
Release: 2023-05-23 13:11:07
Original
359 people have browsed it

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  ");
Copy after login

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);
Copy after login

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));
Copy after login

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);
Copy after login

Output result:

Array
(
    [1] => banana
    [2] => orange
    [3] => pear
)
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!