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');

Solution 1:

array_map and trim can do the job

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

Solution 2:

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

Solution 3:

Multidimensional-proof solution:

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