[英]Problems with alternating colors
I'm having trouble with the script below. 我在下面的脚本时遇到麻烦。 Currently it's just alternating through the colors for the first 4 $i items. 目前,前4个$ i项目只是通过颜色交替显示。 The rest is echo'ed in black. 其余部分以黑色回显。 How do I make it loop through the colors for all the $i values? 如何使所有$ i值的颜色循环显示?
<?php
$colors = array('lightgreen','lightblue','orange','red');
for($i = '0'; $i < '50'; $i++) {
echo " <span style='color: ".$colors[$i].";'><span style='font-family: Webdings; font-size: 30px; '>&#".$i."</span>&#".$i.";</span>";
}
?>
您可以为此使用模运算符(除法后的余数):
echo " <span style='color: ".$colors[$i % 4] ...
[EDIT : based on jeroen' answer which is better than mine] : [编辑:基于jeroen的答案,比我的要好]:
you have 4 colors and you loop 50 times without checking if any color is available. 您有4种颜色,并且循环50次而没有检查是否有任何颜色可用。 You should add a variable to check the number of color and set it to 0 when there are no more available : 您应该添加一个变量来检查颜色数量,并在没有更多可用颜色时将其设置为0:
<?php
$colors = array('lightgreen','lightblue','orange','red');
$nbColors = count($colors);
for($i = '0'; $i < '50'; $i++) {
echo " <span style='color: ".$colors[$i % $nbColors].";'><span style='font-family: Webdings; font-size: 30px; '>&#".$i."</span>&#".$i.";</span>";
}
That allows you to add colors in your initial array without breaking the code. 这样就可以在不破坏代码的情况下在初始数组中添加颜色。
Your array of colours only has four items in it. 您的颜色数组中只有四个项目。 When $i is 3, $colors[$i] will pull out red as it's the fourth one along (remember the array is zero based). 当$ i为3时,$ colors [$ i]将拉出红色,因为它是第四个(记住数组是从零开始的)。 So when $i is equal to 5 there is no colour in the array in that position. 因此,当$ i等于5时,该位置数组中没有颜色。
<?php
$colors = array('lightgreen','lightblue','orange','red');
//Create a variable to store the colour index
$colorPos = 0;
for($i = '0'; $i < '50'; $i++) {
echo " <span style='color: ".$colors[$i].";'><span style='font-family: Webdings; font-size: 30px; '>&#".$i."</span>&#".$i.";</span>";
$colorPos++;
if($colorPos == 4) $colorPos = 0;
}
?>
You could also look in to using next() and reset() on the array: http://php.net/manual/en/function.next.php 您还可以考虑在数组上使用next()和reset(): http : //php.net/manual/en/function.next.php
Thank you to everybody. 谢谢大家 Based on your suggestions I ended up doing like this : 根据您的建议,我最终这样做:
<?php
$colors = array('lightgreen','lightblue','orange','red','magenta');
for($i = '0'; $i < '50'; $i++) {
echo " <span style='color: ".$colors[$i % count($colors)].";'><span style='font-family: Webdings; font-size: 30px; '>&#".$i."</span>&#".$i.";</span>";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.