PHP - Remove whitespace using trim, ltrim and rtrim

by
Jeremy Canfield |
Updated: January 21 2023
| PHP articles
In PHP, there are 3 similar built in functions that can be used to remove whitespace.
- trim - remove whitespace from both the left side and right side of a string
- ltrim - remove whitespace from the left side of a string
- rtrim - remove whitespace from the right side of a string
Take for example the following PHP, where there is whitespace to the left and right of Hello World. var_dump is used to show the $foo variable.
<?php
$foo = " Hello World ";
var_dump ($foo);
?>
Which should return something like this.
string(13) " Hello World "
Here is how you could use trim to remove the whitespace to the left and right of Hello World.
<?php
$foo = " Hello World ";
$foo = trim($foo);
var_dump ($foo);
?>
Which should now return something like this.
string(11) "Hello World"
Did you find this article helpful?
If so, consider buying me a coffee over at