Open In App

How to trim all strings in an array in PHP ?

Given a string array with white spaces, the task is to remove all white spaces from every object of an array.
Examples: 
 

Input: arr = ["Geeks  ", "   for", "  Geeks  "]
Output:
Geeks
for
Geeks

Method 1: Using trim() and array_walk() function: 
 



trim( $string, $charlist )
boolean array_walk( $array, myFunction, $extraParam )

Example: 
 




<?php
 
// Create an array with whitespace
$arr = array( "Geeks  ", "  for", "   Geeks   ");
 
// Print original array
echo "Original Array:\n";
foreach($arr as $key => $value)
    print($arr[$key] . "\n");
 
// Iterate array through array_walk() function
// and use trim() function to remove all
// whitespaces from every array objects
array_walk($arr, create_function('&$val',
                    '$val = trim($val);'));
 
// Print modify array
echo "\nModified Array:\n";
foreach($arr as $key => $value)
    print($arr[$key] . "\n");
     
?>

Output: 

Original Array:
Geeks  
  for
   Geeks   

Modified Array:
Geeks
for
Geeks

 

Method 2: Using trim() and array_map() function: 
 

array_map(functionName, arr1, arr2...)

Example: 
 




<?php
 
// Create an array with whitespace
$arr = array( "Geeks  ", "  for", "   Geeks   ");
 
// Print original array
echo "Original Array:\n";
foreach($arr as $key => $value)
    print($arr[$key] . "\n");
 
// Iterate array through array_map() function
// Using trim() function to remove all
// whitespaces from every array objects
$arr = array_map('trim', $arr);
  
// Print modify array
echo "\nModified Array:\n";
foreach($arr as $key => $value)
    print($arr[$key] . "\n");
     
?>

Output: 
Original Array:
Geeks  
  for
   Geeks   

Modified Array:
Geeks
for
Geeks

 

Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.
Example: 
 




<?php
 
// Create an array with whitespace
$arr = array( "Geeks  ", "  for", "   Geeks   ");
 
// Print original array
echo "Original Array:\n";
foreach($arr as $key => $value)
    print($arr[$key] . "\n");
  
// Print modify array
echo "\nModified Array:\n";
 
// Iterate array through for loop
// Using trim() function to remove all
// whitespaces from every array objects
foreach($arr as $key => $value) {
    $arr[$key] = trim($value);
      
    // Print current object of array
    print($arr[$key] . "\n");
}
     
?>

Output: 
Original Array:
Geeks  
  for
   Geeks   

Modified Array:
Geeks
for
Geeks

 


Article Tags :