PHP randomly select from a list

こ雲淡風輕ζ 提交于 2019-12-23 20:13:03

问题


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(); ?>">

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.

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


回答1:


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

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

And then use array_rand to select one:

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



回答2:


Just create an array of colors and select one entry using rand(0, to) as the index.




回答3:


<?php

function getRandomColor(){
    $a = array('#ff5500', '#000066', '#555555');
    $indice = rand(0, count($a)-1);
    return $a[$indice];
}


来源:https://stackoverflow.com/questions/3461695/php-randomly-select-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!