PHP 从列表中随机选择 [英] PHP randomly select from a list

查看:39
本文介绍了PHP 从列表中随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用随机选择颜色的 PHP 代码:

I am currently working with PHP code that random selects colors:

<div onclick="location.href='<?php the_permalink() ?>';" 
    style="cursor:pointer;background:#<?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?>;" 
    class="post bg thickbox" 
    id="thickbox post-<?php the_ID(); ?>">

我更喜欢在一个 PHP 文件中定义一个首选颜色列表,然后在上面的代码中从该列表中随机抽取一个元素.

What I would prefer to do is define a list of preferred colors in one PHP file, and then randomly sample an element from this list in the code above.

随机抽取这样一个颜色列表的正确 PHP 代码是什么?您将如何定义颜色列表?

What is the correct PHP code for randomly sampling such a list of colors? How would you define the list of colors?

推荐答案

我会像大多数人建议的那样,将您的颜色定义为一个 php 文件中的数组:

I would do like most have suggested, define your colors as an array in one php file:

$colors = array("red", "blue", "#00ff00");

然后使用array_rand选择一个:

...background:<?= $colors[array_rand($colors, 1)] ?>;" class=...

这篇关于PHP 从列表中随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆