PHP chop() Function

What is PHP chop() Function?

If you want to remove whitespaces or specific characters at the end of a string, use PHP chop() function.

Note, a whitespace is any character that renders a space. It includes –

  • An ordinary space (ASCII 32)  – “ ”
  • A tab (ASCII 9) – “\t”
  • A new line (line feed) (ASCII 10) – “\n”
  • A carriage return (ASCII 13) – “\r”
  • The NUL-byte (ASCII 0) – “\0”
  • A vertical tab (ASCII 11) – “\v”

Syntax:

chop(string, characters)

Parameters:

The Function has 1 required parameter and 1 optional parameter-

string (Required): It specifies the string.

characters (Optional): It specifies the characters to be removed. If this parameter (2nd parameter) is empty, the function removes the following from the end of the string-

  • An ordinary space (ASCII 32)  – “ ”
  • A tab (ASCII 9) – “\t”
  • A new line (line feed) (ASCII 10) – “\n”
  • A carriage return (ASCII 13) – “\r”
  • The NUL-byte (ASCII 0) – “\0”
  • A vertical tab (ASCII 11) – “\v”

Return Values:

The function returns the trimmed string.

Examples:

Example 1: Removing trailing spaces-

<?php
$string = "Schools of Web.   ";
echo "The trimmed string is: " . chop($string);
?>

Output:

The trimmed string is: Schools of Web.

Example 2: Removing specific characters from the end of a string.

<?php
$string = "Schools of Web.abcd";
echo "The trimmed string is: " . chop($string, "bacd");
?>

Output:

The trimmed string is: Schools of Web.

Practical Usages of chop() Function:

  • Cleaning the user input.
  • Removing extra spaces from database fields, form data.

Notes on chop() Function:

  • The function chop() is an alias of rtrim() function. So, everything that chop can perform, the rtrim() also can perform those. But, modern developers prefer rtrim() function over chop() function because it is more intuitive and descriptive.
  • The function chop() doesn’t work same as PERL’s chop() function does. PERL’s chop() removes only the last character from a string. If you want to remove just the last character from a string like PERL’s chop() function, use substr() function like this-
    <?php
    $string = "Schools of Web.";
    echo "After removing the last character, the string becomes: " . substr($string, 0, -1);
    ?>
    

    Output:

    After removing the last character, the string becomes: Schools of Web

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP chop() Function

The chop() is a built-in string function in PHP. Use this function to remove spaces or specific set of characters from the end of a string.

Reference:

https://www.php.net/manual/en/function.chop.php