PHP Array Exercises : Remove all white spaces in an array
54. Remove All White Spaces in Array
Write a PHP script to remove all white spaces in an array.
Sample Solution:
PHP Code:
<?php
// Original array with various values including null, empty strings, and whitespace
$my_array = array(15, null, " ", -2, NULL, "", " \n", "Red", 54, "\t");
// Print the original array
print_r($my_array);
// Use array_filter with a custom callback function to create a new array filtering out values that are considered empty
$result = array_filter($my_array, create_function('$x', 'return preg_match("#\S#", $x);'));
// Print the new array with non-empty values
print_r($result);
?>
Output:
Array ( [0] => 15 [1] => [2] => [3] => -2 [4] => [5] => [6] => [7] => Red [8] => 54 [9] => ) Array ( [0] => 15 [3] => -2 [7] => Red [8] => 54 )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to iterate over an array of strings and remove all white spaces from each element.
- Write a PHP function to use str_replace() on each element of an array to eliminate white spaces and return the cleaned array.
- Write a PHP program to apply a callback with array_map that trims and removes inner spaces from each string in an array.
- Write a PHP script to process an array of sentences and output each sentence without any spaces.
Go to:
PREV : Delete Specific Value Using array_filter.
NEXT : Convert String to Array (Trim and Remove Empty Lines).
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.