PHP ltrim | Remove Characters from Beginning of String

PHP ltrim is an inbuilt function in PHP. It removes whitespaces (or other characters) from the beginning of a string. In this article, we will discuss the PHP ltrim Function. Also, we will discuss a few examples of using it.

Related Articles


ltrim($string, $characterList)


The PHP ltrim Function expects two parameters. However, only one parameter is mandatory and the other is optional.

  • $string: The first parameter to the function is the string to operate on. It is a mandatory parameter.
  • $characterList: The second parameter to the function is an optional parameter. It specifies the character list to remove from the string. By default, the function removes all the following characters:
    • “\0” – NULL
    • “\t” – tab
    • “\n” – new line
    • “\x0B” – vertical tab
    • “\r” – carriage return
    • ” ” – ordinary white space

Return Value

The ltrim function in PHP returns the string after removing whitespaces and all other predefined characters from left side (beginning of string).

Note: The function returns an empty string when the argument is a null variable.

PHP ltrim function


Let’s discuss a few examples of using the PHP ltrim function.

Example 1: Removing Whitespaces

For instance, consider a simple string containing whitespaces on both ends.


	$string = '   Simple   string ';
	$trimmedString = ltrim($string);



In the above example, the function removes whitespaces only from the left end. The spaces from on the right side remain as it is.

string(15) "Simple   string "

Example 2: Specifying Characters to Remove

Also, we can specify characters to remove by passing the second parameter.

$str = "Hello World!";
echo $str;
//Remove "He" in "Hello"
echo ltrim($str,"Hed!");

The above example will print the following. You can notice that the function removes the “He” from the beginning of the string. However, the “d!” from the end of the string remains as it is.

Hello World!
llo World!

Example 3: Removing Whitespaces from Array of Strings

Similarly, you can remove whitespaces from an array of strings using PHP array_map. We can pass the ltrim function as callback in array_map function.


$fruit = array('apple','banana ', ' mango ');

$trimmedArray = array_map('ltrim', $fruit);


The above example will print the following:


array(3) {
  string(5) "apple"
  string(7) "banana "
  string(6) "mango "


In conclusion, we discussed the PHP ltrim Function. You can read more about it on PHP Official Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *