PHP Array Exercises : Trim all the elements in an array using array_walk function
35. Trim All Array Elements Using array_walk
Write a PHP script to trim all the elements in an array using array_walk function.
Sample Solution:
PHP Code:
<?php
// Define an array with string values containing extra whitespaces
$colors = array( "Red ", " Green", "Black ", " White ");
// Display the original array using print_r
print_r($colors);
// Use array_walk and create_function to trim whitespaces from each array element
array_walk($colors, create_function('&$val', '$val = trim($val);'));
// Display the modified array after trimming whitespaces
print_r($colors);
?>
Output:
Array ( [0] => Red [1] => Green [2] => Black [3] => White ) Array ( [0] => Red [1] => Green [2] => Black [3] => White )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to trim leading and trailing white spaces from all elements in an array using array_walk and a callback function.
- Write a PHP function to normalize an array of strings by trimming and converting them to lowercase using array_walk.
- Write a PHP program to demonstrate the use of array_walk() to clean up an array with extra spaces and then print the result.
- Write a PHP script to iterate through an array of messy strings, trim each element, and display the cleaned results.
Go to:
PREV : Sort Associative Array (Case-Sensitive by Values).
NEXT : Convert Array Elements to Lower and Upper Case.
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.