I need to fill a 10x10 html table using php code with a random number from 1-10 rand(1,10), then depending on the result paint the cell red if <5 or green if >5. i manually created 10 rows with 10 td each and inside I put echo(rand(1,10)) for each one of them but my syntax is wrong and it looks gross
Asked
Active
Viewed 436 times
0
-
Have you tried anything so far? – Nigel Ren May 02 '19 at 19:02
-
i manually created 10
with 10 – May 02 '19 at 19:06each and inside I put echo(rand(1,10)) for each one of them but my syntax is wrong and it looks gross, I am a php beginner so... -
Welcome to the community Winston. This is an inappropriate question to ask on StackOverflow; members of the community are not here to write your code for you. Please update this question with a description of what you have already tried and an explanation how your chosen solution has not been successful. – Kjata30 May 02 '19 at 19:38
-
thank you for your feedback, I updated my question to fully represent my case – May 02 '19 at 20:00
1 Answers
1
<table>
<tbody>
<?php for ($i = 0; $i < 10; $i++) : ?>
<tr>
<?php for ($k = 0; $k < 10; $k++) : ?>
<?php $num = rand(1, 10); ?>
<td style="color: <?= $num < 5 ? 'red' : 'green'; ?>"><?= $num; ?></td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</tbody>
</table>

really_operator
- 180
- 11
-
this almost did the job, I need the table cell be painted not the number itself, also can you do this using if...else statements instead of the 'red' : 'green' options? – May 02 '19 at 19:28
-
I replaced color with background and it worked, now I only need it be done with if...else statements depending on the inside numbers – May 02 '19 at 19:31
-
My answer uses `if/else` statements based on the inside numbers. It's just using a ternary `if` instead of the standard `if` format. See: https://stackoverflow.com/questions/1506527/how-do-i-use-the-ternary-operator-in-php-as-a-shorthand-for-if-else – really_operator May 02 '19 at 19:33
-
-
The equivalent of `= $num < 5 ? 'red' : 'green'; ?>` with a classic `if/else` would be `` I suggest you read this section of the php docs to get a better understanding: https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary And here is a great article explaining the benefits of ternary operators: https://davidwalsh.name/php-shorthand-if-else-ternary-operators – really_operator May 02 '19 at 20:18