Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove last , in php string

Hello I have this example

I need to delete the last comma

<?php

$numeri = ['I', 'II', 'III', 'IV', 'V'];

$size = count($numeri);
for ($i = $size - 1; $i >= 0; $i--) {
    $a = $numeri[$i]  . ',';
    echo $a;
 
}


?>

V, IV, III , II, I,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But even if I use substr or substrl_replace it deletes all the commas.

>Solution :

You may use the join() function here:

$numeri = ['I', 'II', 'III', 'IV', 'V'];
$output = join(",", array_reverse($numeri));
echo $output;  // V,IV,III,II,I

If you want to stick with a loop approach, then use logic to prepend a comma at each iteration, except for the very first:

$numeri = ['I', 'II', 'III', 'IV', 'V'];

$size = count($numeri);
$a = null;
for ($i = $size - 1; $i >= 0; $i--) {
    if ($a) $a .= ",";
    $a .= $numeri[$i];
}

echo $a;  // V,IV,III,II,I
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading