How to trim all strings in an array in PHP ?

In PHP, you can trim all strings in an array by removing leading and trailing whitespace from each element. There are several methods to achieve this, with array_map() being the most common approach.

Using array_map()

The array_map() function applies the trim() function to each element of the array ?

<?php
    $arr = array(" John ", "Jacob ", " Tom ", " Tim ");
    echo "Array with leading and trailing whitespaces...<br>";
    foreach($arr as $value) {
        echo "Value = '$value'<br>";
    }
    
    $result = array_map('trim', $arr);
    echo "\nUpdated Array...<br>";
    foreach($result as $value) {
        echo "Value = '$value'<br>";
    }
?>
Array with leading and trailing whitespaces...
Value = ' John '
Value = 'Jacob '
Value = ' Tom '
Value = ' Tim '

Updated Array...
Value = 'John'
Value = 'Jacob'
Value = 'Tom'
Value = 'Tim'

Using array_walk()

The array_walk() function modifies the original array in place using a callback function ?

<?php
    $arr = array(" Kevin ", "Katie ", " Angelina ", " Jack ");
    echo "Array with leading and trailing whitespaces...<br>";
    foreach($arr as $value) {
        echo "Value = '$value'<br>";
    }
    
    array_walk($arr, function(&$val) {
        $val = trim($val);
    });
    
    echo "\nUpdated Array...<br>";
    foreach($arr as $value) {
        echo "Value = '$value'<br>";
    }
?>
Array with leading and trailing whitespaces...
Value = ' Kevin '
Value = 'Katie '
Value = ' Angelina '
Value = ' Jack '

Updated Array...
Value = 'Kevin'
Value = 'Katie'
Value = 'Angelina'
Value = 'Jack'

Comparison

Method Modifies Original Returns New Array Best For
array_map() No Yes Creating new trimmed array
array_walk() Yes No Modifying existing array

Conclusion

Use array_map('trim', $array) when you need a new trimmed array, or array_walk() with a trim callback to modify the original array. Both methods effectively remove whitespace from all string elements.

Updated on: 2026-03-15T08:19:13+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements