-4

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,

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

Kida
  • 17
  • 3
  • 2
    _"I need to delete the last comma"_ - a) `rtrim` exists, and b) why did you _add_ it in the first place then? – CBroe Jul 25 '22 at 08:39

3 Answers3

1

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

substring will work if you do operation after for loop

<?php

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

$size = count($numeri);
for ($i = $size - 1; $i >= 0; $i--) {
    $a=$a.$numeri[$i]  . ',';
}
$a=substr($a,0,strlen($a)-1);
echo $a;
?>
-3
$mystring='['I', 'II', 'III', 'IV', 'V']';
$myString = trim($myString, ',');
 echo $myString; 
Kezman10
  • 3
  • 3
  • `$mystring` is an invalid string that will cause a "parse error". `$myString` doesn't exist yet when using `trim`, you named it `$mystring`. `['I', 'II', 'III', 'IV', 'V']` should be an array, not a string. `trim` will _not_ remove the last comma here – brombeer Jul 25 '22 at 08:43