Skip to content

array_trim

Tonya Mork edited this page Mar 12, 2017 · 2 revisions

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.

Syntax

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

When to Use

Use this function when you need to trim multiple elements in an array, such as when processing a form or query strings.

For Example

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

Single Depth

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

Go Deeper

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

« Back to Array API

Clone this wiki locally