-
Notifications
You must be signed in to change notification settings - Fork 1
array_trim
The array_trim()
function applies the PHP trim()
function to each element's string value in the subject array. This function will strip whitespace (or other characters) from the beginning and end of each string.
The intent of this function is to reduce your code when you need to trim the elements within an array.
You can escape one level of the array, or for deeper arrays, you can set the second argument to true.
Note: The original subject array is changed when running this function, as it's passed by reference.
array array_trim(
array &$subjectArray,
[ bool $goDeep = false ]
);
Where:
$subjectArray
is the array to work on
$goDeep
when true
, each depth level of the array is processed
Use this function when you need to trim multiple elements in an array, such as when processing a form or query strings.
Let's use this given dataset for our examples:
$dataSet = array(
'user_id' => 101,
'name' => ' Tonya ',
'email' => ' <a:mailto="[email protected]">[email protected] </a> ',
'social' => array(
'twitter' => ' <a href="https://twitter.com/hellofromtonya">@hellofromtonya </a> ',
'website' => ' <a href="https://foo.com">https://foo.com </a> ',
),
'has_access' => true,
);
Let's trim the first depth level of the array:
array_trim( $dataSet );
Running this code changes the $dataSet
array to:
array(
'user_id' => 101,
'name' => 'Tonya',
'email' => '<a:mailto="[email protected]">[email protected] </a>',
'social' => array(
'twitter' => ' <a href="https://twitter.com/hellofromtonya">@hellofromtonya </a> ',
'website' => ' <a href="https://foo.com">https://foo.com </a> ',
),
'has_access' => true,
);
Let's clean the entire array by specifying the second argument as true
:
array_trim( $dataSet, true );
Running this code changes the $dataSet
array to:
array(
'user_id' => 101,
'name' => 'Tonya',
'email' => '<a:mailto="[email protected]">[email protected] </a>',
'social' => array(
'twitter' => '<a href="https://twitter.com/hellofromtonya">@hellofromtonya </a>',
'website' => '<a href="https://foo.com">https://foo.com </a>',
),
'has_access' => true,
);