PHP 8.5 chop() Function Use With Example

There is no specific new feature or change for chop() in PHP 8.5. According to the official PHP documentation, chop() remains an alias of the rtrim() function, with stable behavior, and is primarily used to remove whitespace or specified characters from the right end of a string.

Core Usage and Examples

The purpose of chop() is exactly the same as rtrim(). It is recommended to use rtrim() in new code, as the name is clearer and more readable.

Example 1: Removing trailing whitespace or newlines.

<?php
$str = "Hello World! ";
// Output will remove the trailing newlines, resulting in "Hello World!"
echo chop($str);
?>

When no second parameter is specified, it defaults to removing these characters: (NULL), (tab), (newline), x0B (vertical tab), (carriage return), and spaces.

Example 2: Removing specified characters.

<?php
$str = "Hello World!";
// Remove "World!" from the right end, output "Hello "
echo chop($str, "World!");
?>

Example 3: Cleaning up paths or redundant characters.

<?php
$path = "/Users/My Docs/PHP/file.txt///";
// Remove redundant slashes from the right end
$cleanPath = chop($path, "/");
echo $cleanPath; // Output: /Users/My Docs/PHP/file.txt
?>

11 Views