PHP chop() function returns a string after removing the specified characters from an end. The chop() function is an alias of rtrim() function.
How to Remove Whitespace from String in PHP
To remove whitespace from a string in PHP, use the chop() function. The chop() is a built-in PHP string function that removes whitespaces or other predefined characters from the right end of the string. The chop() function removes any other specified characters from the end of the string.
Syntax
The syntax of the PHP String chop() function is following.
string chop($string, $character)
Parameters
The $string argument is which is needed to be checked.
The $character argument specifies the character needed to be removed from a given string. If the parameter is not specified, then NULL, tab, newline, vertical tab, carriage return, and ordinary white space are removed automatically.
See the following characters are removed if a charlist parameter is empty:
- “\0” – NULL
- “\t” – tab
- “\n” – newline
- “\x0B” – vertical tab
- “\r” – carriage return
- ” ” – ordinary white space
Return value
The return type of the chop() function is a string.
Example
See the code example.
<?php $site = 'AppDividend'; echo chop($site, 'end');
See the output.
➜ pro php app.php AppDivi ➜ pro
Passing no parameters
Since no character parameter is mentioned in the code below, the newlines will automatically be removed from a given string.
<?php $statement = "Hello Millie! \n nice to meet you \n \n"; echo chop($statement);
See the output.
➜ pro php app.php Hello Millie! nice to meet you ➜ pro
How to remove the last character from string in PHP
To remove the last character from a string in PHP, use the chop() function.
<?php $entrepreneur = "MillieBobbyBrown"; echo chop($entrepreneur, 'n');
See the output.
➜ pro php app.php MillieBobbyBrow ➜ pro
You can see that the last character “n” from the string is removed.
Okay, let’s use the rtrim() function.
rtrim() in PHP
The rtrim() is a built-in PHP function that removes the characters from the right side of a string.
<?php $entrepreneur = "MillieBobbyBrown"; echo rtrim($entrepreneur, 'n');
See the output.
➜ pro php app.php MillieBobbyBrow ➜ pro
That’s it for PHP chop() function.