How to trim white spaces of array values in php

后端 未结 12 1374
旧巷少年郎
旧巷少年郎 2020-11-28 19:30

I have an array as follows

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

I want an array which conta

相关标签:
12条回答
  • 2020-11-28 19:54

    Multidimensional-proof solution:

    array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-28 20:03

    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

    0 讨论(0)
  • 2020-11-28 20:05

    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 ) )
    
    0 讨论(0)
  • 2020-11-28 20:09

    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);
    
    0 讨论(0)
  • 2020-11-28 20:10

    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);
    
    0 讨论(0)
提交回复
热议问题