[php] How to trim white spaces of array values in php

I have an array as follows

$fruit = array('  apple ','banana   ', ' , ',     '            cranberry ');

I want an array which contains the values without the white spaces on either sides but it can contain empty values how to do this in php.the output array should be like this

$fruit = array('apple','banana', ',', 'cranberry');

This question is related to php arrays

The answer is


If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

foreach($array as $key => $value)
{
    $array[$key] = trim($value);
    print("-");
    print($array[$key]);
    print("-");
    print("<br>");
}

If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

$array = array_map('trim', $array);

If the array is multidimensional, this will work great:

//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
   if($data == null)
       return null;

   if(is_array($data)){
       return array_map('trimData', $data);
   }else return trim($data);
}

one sample test is like this:

$arr=[" aaa ", " b  ", "m    ", ["  .e  ", "    12 3", "9 0    0 0   "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )

function trimArray(&$value) 
{ 
    $value = trim($value); 
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');

by using array_walk function, we can remove space from array elements and elements return the result in same array.


Multidimensional-proof solution:

array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});

Trim in array_map change type if you have NULL in value.

Better way to do it:

$result = array_map(function($v){ 
  return is_string($v)?trim($v):$v; 
}, $array);

I had trouble with the existing answers when using multidimensional arrays. This solution works for me.

if (is_array($array)) {
    foreach ($array as $key => $val) {
        $array[$key] = trim($val);
    }
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function generateRandomSpaces() {
    $output = '';
    $i = rand(1, 10);
    for ($j = 0; $j <= $i; $j++) {
        $output .= " ";
    }   

    return $output;
}

// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
    $array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces(); 
}

// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";

// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk    : " . $time . " seconds\n"; 

// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    foreach ($array as $index => $elem) {
        $array[$index] = trim($elem);
    }
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";

// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    for ($j = 0; $j < count($array) - 1; $j++) { 
        $array[$j] = trim($array[$j]);
    }
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";

The output of the code above is:

Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds

This values of course may change but I would say foreach is the best option.


$fruit= array_map('trim', $fruit);

simply you can use regex to trim all spaces or minify your array items

$array = array_map(function ($item) {
    return preg_replace('/\s+/', '', $item);
}, $array);

array_walk() can be used with trim() to trim array

<?php
function trim_value(&$value) 
{ 
    $value = trim($value); 
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

See 2nd example at http://www.php.net/manual/en/function.trim.php


array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:

$data = array_map(
    function ($item) {
        return is_string($item) ? trim($item) : $item;
    },
    $data
);