Use substr() with a negative length when you need to remove a known number of trailing bytes. Check the input assumptions first when strings may be empty or contain multibyte characters.
$value = 'invoice.csv';$withoutLastFour = substr($value, 0, -4);echo $withoutLastFour; // invoice
When the length is unknown, use a negative length with substr(). This operates on bytes, not Unicode characters. For multibyte text, use mb_substr() when the mbstring extension is available.
$q = 'sample-text';$q = substr($q, 0, -3);echo $q; // sample-t
Do not build SQL by appending user input and trimming a trailing comma. The query below uses placeholders so the values can be bound as parameters:
SELECT * FROM table_name WHERE student_id IN (?, ?, ?, ?)
$ids = [1, 2, 3, 4];$placeholders = implode(', ', array_fill(0, count($ids), '?'));$sql = 'SELECT * FROM table_name WHERE student_id IN (' . $placeholders . ')';// Prepare $sql and pass $ids to execute(); never append untrusted IDs to SQL.
If your goal is only to format comma-separated data, implode() avoids generating a trailing comma in the first place:
$items = ['1', '2', '3', '4'];$list = implode(',', $items);echo $list; // 1,2,3,4 (data formatting only, not SQL parameters)
See implode() for joining values, and substr() for slicing.
We can easily extract the last few characters of a string using substr() by providing a negative offset:
$string = "Hello, World!";$last_chars = substr($string, -4);echo $last_chars; // rld!
This example demonstrates extracting the last word from a sentence using strrpos() and substr():
$sentence = 'PHP is a popular scripting language';$position = strrpos($sentence, ' ');$last_word = $position === false ? $sentence : substr($sentence, $position + 1);echo $last_word; // language
You can remove the last character only if it is a specific value (e.g., period):
$sentence = 'This is a sentence.';if (str_ends_with($sentence, '.')) { // PHP 8+
$sentence = substr($sentence, 0, -1);}echo $sentence; // This is a sentence
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.