There is a function that generates 4 numbers and displays them separated by commas. For example, 13, 15, 1, 8,. How can I remove the last comma?

function random($min, $max) { for ($i = 0; $i < 4; $i++) { echo mt_rand($min, $max) . ", "; } } 

    5 answers 5

    There are several options, for example, to collect all the numbers, then display them:

     function random($min, $max) { $values = array(); for ($i=0; $i<4; $i++){ array_push($values, mt_rand($min, $max)); } echo implode(', ', $values); } 

      Could be so : )

       function random($min, $max) { printf( '%d, %d, %d, %d', mt_rand($min, $max), mt_rand($min, $max), mt_rand($min, $max), mt_rand($min, $max) ); } 

        As an option: Generate 3 numbers, and 4 without a comma

           function random($min, $max) { for ($i = 0; $i < 4; $i++) { echo mt_rand($min, $max) . ($i < 3 ? ',' : ''); } } 

            Just cut the last character:

             function random($min, $max) { for ($i=0; $i<4; $i++){ $a .= mt_rand($min, $max).", "; } echo substr($a, 0, -1); } 
            • 2
              Then it is worth cutting the last two characters. - Regent