422
422

Reputation: 5770

Generate random word from two known words

I can do this with numbers:

<?=number_format(mt_rand(0,1));?>

What I want to do is, instead of 0 or 1, echo the words firstclass or secondclass.

This is because I cannot use numbers as class identifiers in CSS.

Essentially, this is just for displaying random stuff within a list and prepending the class identifier with either firstclass or secondclass.

.firstclass {display:none;}

I am not ace with PHP, so I guess I need to set up an array, and somehow attribute:

0 = firstclass
1 = secondclass

within the array, so that I can get my little test script working.

Any suggestions?

Upvotes: 3

Views: 704

Answers (5)

s_ha_dum
s_ha_dum

Reputation: 2850

Or...

class="a-prefix-<?=number_format(mt_rand(0,1));?>"

CSS classes have to start with an underscore, a dash, or a letter but you can have numbers after that.

Upvotes: 3

PhearOfRayne
PhearOfRayne

Reputation: 5050

If you going to say that 0 = firstclass, 1 = secondclass why not just use array_rand like this:

$classes = array(
    'firstclass',
    'secondclass'
);

$randClass = $classes[array_rand($classes)];

echo $randClass;

This will also give you the possibility to add more classes if you ever needed

Upvotes: 2

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

<?php echo (mt_rand(0,1) == 0 ? 'firstclass' : 'secondclass'); ?>

Upvotes: 5

mellamokb
mellamokb

Reputation: 56769

You can use a ternary-style if statement if you only have two possibilities:

<?=(mt_rand(0,1) == 0) ? 'firstclass' : 'secondclass'?>

Upvotes: 2

ddinchev
ddinchev

Reputation: 34673

Like this? :

$words = array('firstclass', 'secondclass');
$randomWord = $words[mt_rand(0,1)];

Upvotes: 4

Related Questions