PHP trim() function

The trim() function is used to remove white space and other predefined characters from both sides of a string.

Syntax

trim (  $string , $character) : string

Parameters

Parameter Name Descrption
$string Required, String to be remove whitespace/predefined characters
$character

Optional, The trim() function return the string with whitespace removed, if second parameter will not passed then trim() will strip these characters:
" " - an ordinary space
"\t" - a tab
"\n" - new line
"\r" - carriage return
"\0" - NUL-byte
"\x0B" - vertical tab.

Return Value

The trimmed string

trim() examples

$string1 = " this is string "; //length : 16
$trim_string1 = trim($string1);
var_dump($trim_string1);
//output : 'this is string' (length=14)

$text_trim =  "\t\tThis is string ";
var_dump($text_trim); 
//output : '		This is string ' (length=17)

$trimmed = trim($text_trim);
var_dump($trimmed);
// output : 'This is string' (length=14)

$text_trim =  "Trim function in PHP";
$trimmed = trim($text_trim,'TP');
var_dump($trimmed);
// output : 'rim function in PH' (length=18)

$text_trim =  "Trim function in PHPT";
$trimmed = trim($text_trim,'T');
var_dump($trimmed);
//output : 'rim function in PHP' (length=19)

Remove the whitespace of array values with the use of array_map(), return the new array

$lang = array('PHP ',' JS ',' NodeJS');
var_dump($lang);
//output 
array (size=3)
  0 => string 'PHP ' (length=4)
  1 => string ' JS ' (length=4)
  2 => string ' NodeJS' (length=7)
  
$newarray = array_map('trim', $lang);
var_dump($newarray);
//output 
array (size=3)
  0 => string 'PHP' (length=3)
  1 => string 'JS' (length=2)
  2 => string 'NodeJS' (length=6)

Remove the whitespace of array values with the use of array_walk() , return the same array

function trim_array_value(&$value) 
{ 
    $value = trim($value); 
}
$lang = array('PHP ',' JS ',' NodeJS');
array_walk($lang, 'trim_array_value');
var_dump($lang);

Trimming the multidimensional array values in PHP with trim()

$lang = array('PHP ',' JS ',' NodeJS','frontend'=>array(' html ','CSS '));
function TrimMultiDimensional(&$array)
{
	foreach($array as &$value)
	is_array($value) ? TrimMultiDimensional($value):$value=trim($value);
	unset($value);
}
TrimMultiDimensional($lang);
var_dump($lang);

Related Functions

  • ltrim(): Strip whitespace (or other characters) from the beginning of a string
  • rtrim(): Strip whitespace (or other characters) from the end of a string