Avatar ·

How to remove the last delimiter at the end of a string in PHP?

Hi everyone! I'm a beginner in PHP and writing a small script to generate a CSV string from a data array. I have an array with usernames, and I want to join them into a comma-separated string. I'm using a foreach loop to iterate through the array and add each name to the string with a trailing comma. Here's my code: ```php $users = ['Alice', 'Bob', 'Charlie', 'Diana']; $csv = ''; foreach ($users as $user) { $csv .= $user . ','; } echo $csv; // Outputs: Alice,Bob,Charlie,Diana, ``` The problem is that there's an extra comma at the end of the string. Because of this, when I try to use this string in a CSV file or pass it to another function, errors occur — the last element ends up empty or gets parsed incorrectly. I understand that I can somehow trim the last character, but I don't know how.