PHP is the best way to print a multiplication table

Basic PHP. I decided to print a list of 10 multiples of 17.5, for example:

17.5 | 35 | 52.5 | 70 | 87.5 | 105 | 122.5 | 140 | 157.5 | 175 |

So, I used this loop first:

<?php
$number = 17.5;
$result = 0;
$i = 0;
while ($i < 10) {
  $result += $number;
  echo $result.' | ';
  $i++;  }

      

Well it works. Then I switched to this, which is pretty short:

$i = 1;
$result = 17.5;
while ($i <= 10) {
  echo $result * $i.' | ';
  $i++;  }

      

But I'm sure there is a better way. What's the best syntax?

+3


source to share


4 answers


$results = array();
for ($i = 1; $i <= 10; $i++){
    $results[] = $i * 17.5;
}
echo implode(' | ', $results);

      

Or better



echo implode(' | ', range(17.5, 17.5*10, 17.5));

      

+3


source


There are many quicker ways to achieve this. Take this simple loop for

for example:

$num = '17.5';

for($i = 1; $i <=10; $i++) {
    $array[] = $i * $num; 
}
echo implode(' | ', $array);

      



Example

+3


source


$result = 17.5;
for($i=1; $i<=10; $i++){
    echo  ($i * $result) .' | ';
}

      

+1


source


I like my best:

$s = $t = '17.5';
while($s < $t*10){
    echo ($s += $t).' | ';
}

      

+1


source







All Articles