为此,您可以将for循环与某些条件一起使用。
PHP代码如下-
<!DOCTYPE html> <html> <body> <?php $arrayList = []; for ($counter = 0; $counter < 5; $counter++) { ($counter%2) ? ($arrayList[] = $counter) : ($arrayList[] = "Even"); } for ($counter = 0; $counter < 5; $counter++) { echo $arrayList[$counter]," "; } ?> </body> </html>
输出结果
Even 1 Even 3 Even
上方,对于第0个索引,显示文本“偶数”,第2个和第4个索引也是如此。