PHP chop() Function

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The chop() function strips characters from the end of a string. It is an alias of rtrim() and is handy for cleaning trailing spaces, tabs, or custom characters left over from user input or file reads.

01

Right Side Only

Trims the end, not the start.

02

rtrim() Alias

Identical behavior.

03

Default Whitespace

Spaces, tabs, newlines.

04

Custom Charlist

Pick characters to strip.

05

User Input

Clean pasted text.

06

vs trim()

End-only vs both sides.

Definition and Usage

In PHP, chop() removes characters from the right end of a string and returns the result as a new string. With no second argument, it strips standard whitespace characters. For example, chop("Hello, World! ") returns "Hello, World!".

💡
Beginner Tip

chop() only affects the trailing end. Leading spaces stay put. If you need both sides cleaned, use trim(). If you need only the left side, use ltrim(). Modern code often prefers the clearer name rtrim() over chop().

📝 Syntax

The chop() function accepts one required and one optional parameter:

PHP
string chop(string $string, string $characters = " \t\n\r\0\x0B")

Parameters

  • $string — the input string to trim from the right.
  • $characters (optional) — a list of characters to remove from the end. If omitted, PHP strips whitespace: space, tab, newline, carriage return, NUL, and vertical tab.

Return Value

Returns a new string with trailing characters removed. The original $string is not modified.

⚡ Quick Reference

InputCallResult
"Hello "chop($s)"Hello"
" Hello "chop($s)" Hello" (leading kept)
"file.txt..."chop($s, ".")"file.txt"
"data---"chop($s, "-")"data"
""chop($s)""
Basic
chop($str)

Strip trailing whitespace

Custom
chop($str, " \t")

Spaces and tabs only

Alias
rtrim($str)

Same as chop()

Both Sides
trim($str)

Start and end

Examples Gallery

Run these examples in any PHP 7+ environment. Each one shows a common pattern beginners encounter with chop().

📚 Getting Started

Remove trailing whitespace from the end of a string.

Example 1 — Strip Trailing Spaces

The most common use: clean up extra spaces at the end of a line of text.

PHP
<?php
$text    = "Hello, World!   ";
$trimmed = chop($text);

echo "Before: '$text'\n";
echo "After:  '$trimmed'\n";
?>

How It Works

  • The three trailing spaces are removed from the right end.
  • $text still holds the original value; assign the result to a new variable.
  • Characters in the middle of the string are never touched.

Example 2 — Custom Character List

Pass a second argument to strip only specific trailing characters—here, spaces and tabs.

PHP
<?php
$text    = "   PHP is awesome   \t";
$trimmed = chop($text, " \t");

echo "Result: '$trimmed'\n";
?>

How It Works

Only the trailing spaces and tab are removed. The three leading spaces remain because chop() never trims the beginning—unlike trim().

📈 Practical Patterns

Real-world trimming scenarios in PHP applications.

Example 3 — Remove Trailing Dots or Slashes

Use a custom charlist to strip punctuation from the end of filenames or URLs.

PHP
<?php
$filename = "report.pdf...";
$clean    = chop($filename, ".");

$path     = "/api/users///";
$normalized = chop($path, "/");

echo "Filename: $clean\n";
echo "Path:     $normalized\n";
?>

How It Works

PHP removes every consecutive trailing character that appears in the charlist—all three dots and all three slashes—until it hits a character not in the list.

Example 4 — chop() vs trim() vs ltrim()

See how the three trimming functions behave differently on the same input.

PHP
<?php
$s = "  hello world  ";

echo "chop():  '" . chop($s) . "'\n";
echo "ltrim(): '" . ltrim($s) . "'\n";
echo "trim():  '" . trim($s) . "'\n";
echo "rtrim(): '" . rtrim($s) . "'\n";
?>

How It Works

  • chop() and rtrim() produce the same result—right side only.
  • ltrim() removes from the left only.
  • trim() removes from both ends.

Example 5 — Cleaning Form Input

Users often add accidental spaces or newlines when pasting into a form field. Clean the trailing junk before saving.

PHP
<?php
// Simulated POST data with trailing newline and spaces
$email = "user@example.com  \n";

$cleanEmail = chop($email);

echo "Raw:   '$email'\n";
echo "Clean: '$cleanEmail'\n";
echo "Valid: " . (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL) ? "yes\n" : "no\n");
?>

How It Works

Trailing whitespace and the newline are stripped from the end. For full cleanup of pasted input, you may still want trim() to also remove leading spaces.

🚀 Common Use Cases

  • Form input cleanup — remove trailing spaces or newlines from emails, usernames, or comments.
  • File line processing — strip newline characters from lines read with fgets().
  • URL/path normalization — remove trailing slashes from directory paths.
  • CSV or log parsing — clean trailing delimiters or padding characters.
  • Legacy code — recognize chop() as identical to rtrim() when reading older PHP projects.

🧠 How chop() Works

1

PHP reads the string

You pass the input string and an optional list of characters to strip from the end.

Input
2

Trailing characters are removed

PHP scans from the right end and removes every character that matches the charlist until a non-matching character is found.

Transform
3

A trimmed string is returned

The original string is unchanged. Assign the result or use it inline.

Output
=

Clean trailing end

Ready for validation, storage, or further string processing.

📝 Notes

  • chop() is an alias of rtrim()—they are 100% identical.
  • Only the right end is trimmed. Leading characters are never removed.
  • The charlist is a set of individual characters, not a word or substring to match.
  • PHP removes all consecutive trailing matches, not just one character.
  • For most new code, rtrim() is preferred because the name clearly means “right trim.”

Conclusion

The chop() function is a simple way to remove unwanted characters from the end of a string in PHP. Whether you are cleaning user input, normalizing paths, or processing file lines, it gives you precise right-side trimming with an optional custom character list.

Remember: chop() = rtrim() (right only), ltrim() (left only), trim() (both sides). Pick the function that matches where your extra characters appear.

💡 Best Practices

✅ Do

  • Use chop() when only trailing characters need removal
  • Prefer rtrim() in new code for clearer intent
  • Assign the returned string to a variable
  • Use trim() when both ends may have extra whitespace
  • Validate cleaned input after trimming

❌ Don’t

  • Expect chop() to remove leading spaces
  • Assume the original string changes in place
  • Confuse chop() with trim()
  • Pass a “word” as charlist expecting substring removal
  • Rely on trimming alone for security sanitization

Key Takeaways

Knowledge Unlocked

Five things to remember about chop()

Use these points whenever you trim strings in PHP.

5
Core concepts
🔄 02

rtrim() Alias

Identical behavior.

Relation
🛠 03

Default Whitespace

Space, tab, newline…

Syntax
👤 04

Form Cleanup

Trailing paste junk.

Use case
05

Not trim()

trim() = both sides.

Compare

❓ Frequently Asked Questions

chop() removes characters from the end (right side) of a string. By default it strips whitespace characters such as spaces, tabs, and newlines. It does not remove anything from the beginning of the string.
string chop(string $string, string $characters = " \t\n\r\0\x0B"). The first argument is the input string; the optional second argument lists which characters to strip from the end.
Yes. chop() is an alias of rtrim(). They behave identically—both remove characters from the right end of a string only.
chop() (like rtrim()) removes characters from the end only. trim() removes characters from both the beginning and the end. Use chop() when trailing junk is the problem; use trim() when you need both sides cleaned.
When you omit the second argument, chop() removes space, tab (\t), newline (\n), carriage return (\r), NUL byte (\0), and vertical tab (\x0B).
No. chop() returns a new trimmed string. The original variable stays unchanged because PHP strings are passed by value.

Explore More PHP String Functions

Continue with chr(), explode(), and the rest of the string function reference.

Next: chr() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful