PHP clears spaces at both ends of all strings in the array

Source: Internet
Author: User
This article describes how to clear spaces at both ends of all strings in the PHP array. it involves operations on PHP arrays and string operations, which are of great practical value, for more information about how to clear spaces at both ends of all strings in the PHP array, see the example in this article. The specific implementation method is as follows:

In general, there are many implementation methods to clear spaces in strings in php, but we cannot simply use these methods to clear the code before and after all values in the array, in this example, the array_map function exclusive to php is used to traverse and clear spaces at both ends of all strings in the array.

The specific implementation code is as follows:

The 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 your 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;
}
*/

// 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 will help you with PHP programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.