Так что, если вам действительно нужно случайное приветствие с соответствующим цветом для каждой строки таблицы, которую вы строите, то вам нужна функция, которая сможет выбрать случайную в любое время, когда вам это нужно. Чтобы получить случайную запись, мы будем использовать rand
:
function getRandomGreeting(): string
{
// we immediately define a color for each greeting
// that way we don't need an if condition later comparing the result we got
$greetings = [
['greeting' => 'Hi', 'color' => 'green'],
['greeting' => 'Welcome', 'color' => 'red'],
];
/*
Here we choose a random number between 0 (because arrays are zero-indexed)
and length - 1 (for the same reason). That will give us a random index
which we use to pick a random element of the array.
Why did I make this dynamic?
Why not just put 1 if I know indices go from 0 to 1?
This way, if you ever need to add another greeting, you don't need
to change anything in the logic of the function. Simply add a greeting
to the array and it works!
*/
$chosenGreeting = $greetings[rand(0, count($greetings) - 1)];
return '<b style="color:'.$chosenGreeting['color'].';">'.$chosenGreeting['greeting'].'</b>';
}
А затем внутри вашей таблицы вам просто нужно вызвать функцию:
<td><?= getRandomGreeting() ?> [...other content of cell...]</td>
Обратите внимание, что <?=
является сокращением для <?php echo
.