PHP Array Exercises : Remove all white spaces in an array
PHP Array: Exercise-54 with Solution
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:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP script to delete a specific value from an array using array_filter() function.
Next: Write a PHP function to convert a string to an array (trimming every line and remove empty lines).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-array-exercise-54.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics