php endforeach每个字符串随机颜色

时间:2018-06-19 08:23:39

标签: php

我试图给每个字符串一个随机颜色。但是所有颜色都是相同的,只会在页面加载时发生变化。

这是我的代码

<?php
$variable = 'value1, value2, value3, value4, value5';
$colors= array("pink", "light-blue", "indigo", "purple", "orange", "green");
$random_color = $colors[array_rand($colors)];
$arrs = explode(',', $variable);

foreach($arrs as $arr): ?>
    <span style="color: <?php echo $random_color; ?>"><?php echo $arr ?></span>
<?php endforeach; ?>

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

$random_color = $colors[array_rand($colors)];放入for循环中:

$variable = 'value1, value2, value3, value4, value5';
$colors= array("pink", "light-blue", "indigo", "purple", "orange", "green");
$arrs = explode(',', $variable);

foreach($arrs as $arr): 
$random_color = $colors[array_rand($colors)];
?>

    <span style="color: <?php echo $random_color; ?>"><?php echo $arr ?></span>
<?php endforeach; ?>