V
V
Vahthere2018-06-16 14:58:45
PHP
Vahthere, 2018-06-16 14:58:45

How to generate a random number in PHP?

You need to:
1. Generate a random number in the range from 10 to 220;
2. Put the resulting number into a variable;
3. Multiply the resulting number by 12;
4. Insert a random number from step 1 and obtained in step 3
Random number from step 1
Result obtained in step 3
This does not work:

<?php
      $basik = rand(10,220);
      $bonus = 12;
      $result = $basik * $bonus;
      echo $result, " ", "баллов" <br/>;
      echo $basik, " ",  "начислено";
  ?>

<div id="random">   echo $result, " ", "баллов" <br/>;</div>

<div id="result">   echo $basik, " ",  "начислено";</div>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
eternalfire, 2018-06-16
@eternalfire

<?php
      $basik = rand(10,220);
      $bonus = 12;
      $result = $basik * $bonus;
?>

<div id="result">"<?= $basik ?>" начислено</div>

R
Roman Terekhin, 2018-06-16
@RomaZveR

The code for working with numbers is correct, but the output is not.

echo $result.' баллов<br/>';
echo $basik.' начислено';

+ If the output is in a template, then
<div id="random"><?=$result;?> баллов</div>
<div id="result"><?=$basik;?> начислено</div>

Y
Yan-s, 2018-06-16
@Yan-s

Firstly. You have to say what doesn't work for you. Secondly, when you try to run the code, you should have received an error message indicating the line and the problem.
Two errors:
1. In a string echo $result, " ", "баллов" <br/>;- <br/>Must be inside quotes here. All string values ​​in PHP must be inside quotes.
2.

<div id="random">   echo $result, " ", "баллов" <br/>;</div>
You do not distinguish between PHP and HTML at all. To do a PHP embed into HTML, you first need to wrap it in a <?php ?>.
Other jambs
- rand () - gives a bad random, has problems on different platforms. mt_rand() should be used instead, and for cryptographically secure random_int() values ​​- overwriting
you echo $basik, " ", "начислено";can , " "push a space to the next value echo $basik, " начислено";- equivalent but cleaner.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question