douzhen1234 2018-06-19 08:23
浏览 62

php endforeach每个字符串随机颜色

I am trying to give every string a random color. But all the colors are the same and only change on page load.

Here is my code

<?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; ?>

Someone knows how to fix this?

  • 写回答

1条回答 默认 最新

  • dongpaipu8394 2018-06-19 08:56
    关注

    Put $random_color = $colors[array_rand($colors)]; inside for loop:

    $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; ?>
    
    评论

报告相同问题?