PHP Method for clearing spaces at both ends of all strings in an array

  • 2021-07-22 09:07:24
  • OfStack

This article describes the example of PHP to clear the array of all the string space at both ends of the method, to share for your reference. The specific implementation method is as follows:

1 Generally speaking, we can have many implementation methods to clear the spaces in strings in php, but we can't simply use these methods before and after clearing all the values in the array. This example mainly uses array_map function unique to php to traverse and clear the spaces at both ends of all strings in the array.

The specific implementation code is as follows:

function TrimArray($Input){
    if (!is_array($Input))
        return trim($Input);
    return array_map('TrimArray', $Input);
}
/*
Old version (v0.1): The old version is for everyone as a comparative reference:
function TrimArray($arr){
    if (!is_array($arr)){ return $arr; }
    while (list($key, $value) = each($arr)){
        if (is_array($value)){
            $arr[$key] = TrimArray($value);
        }
        else {
            $arr[$key] = trim($value);
        }
    }
    return $arr;
}
*/

// Example demo:
$DirtyArray = array(
    'Key1' => ' Value 1 ',
    'Key2' => '      Value 2      ',
    'Key3' => array(
        '   Child Array Item 1 ',
        '   Child Array Item 2'
    )
);
$CleanArray = TrimArray($DirtyArray);
var_dump($CleanArray);
 
Result will be:
array(3) {
  ["Key1"]=>
  string(7) "Value 1"
  ["Key2"]=>
  string(7) "Value 2"
  ["Key3"]=>
  array(2) {
    [0]=>
    string(18) "Child Array Item 1"
    [1]=>
    string(18) "Child Array Item 2"
  }
}

I hope this article is helpful to everyone's PHP programming.


Related articles: