Simple Tutorials for Smart Learning
The chop() function in PHP removes whitespace or specific characters from the end of a string. It’s an alias of the rtrim() function and is primarily used for trimming unwanted trailing characters efficiently.
chop()
rtrim()
string chop( string $string [, string $character_mask ] )
<?php $text = "Hello World "; $result = chop($text); echo "Original: '$text'\nTrimmed: '$result'"; ?>
Output:
Original: 'Hello World ' Trimmed: 'Hello World'
You can specify characters to remove using the second parameter.
<?php $text = "Hello World!!!"; $result = chop($text, "!"); echo $result; ?>
Output
Hello World
The chop() function removes these characters by default:
\t
\n
\r
\0
\x0B
<?php $input = " PHP chop() function guide "; echo "'" . chop($input) . "'"; ?>
' PHP chop() function guide'
<?php $url = "https://example.com////"; $cleanUrl = chop($url, "/"); echo $cleanUrl; ?>
https://example.com
<?php $text = "Hello PHP\n"; echo "'" . chop($text) . "'"; ?>
'Hello PHP'
Use for Trailing Cleanup Only:The chop() function focuses on trimming the end of a string. For full trimming, use trim().
trim()
Default Whitespace Removal:Rely on the default behavior unless specific characters need to be trimmed.
Avoid Ambiguity:Use rtrim() in modern codebases for better readability, as it is more commonly recognized.
ltrim()
Using chop() Instead of trim():
Ignoring Default Behavior: