3

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
422
  • 5,714
  • 23
  • 83
  • 139
  • If you want to obtain some integer in [0,9] just multiply with 10^n, and after calculate modulo 10. – Mihai8 Jan 01 '13 at 23:09

5 Answers5

5
<?php echo (mt_rand(0,1) == 0 ? 'firstclass' : 'secondclass'); ?>
Wojciech Zylinski
  • 1,995
  • 13
  • 19
4

Like this? :

$words = array('firstclass', 'secondclass');
$randomWord = $words[mt_rand(0,1)];
ddinchev
  • 33,683
  • 28
  • 88
  • 133
3

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.

s_ha_dum
  • 2,840
  • 2
  • 18
  • 23
2

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

<?=(mt_rand(0,1) == 0) ? 'firstclass' : 'secondclass'?>
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • It's recommended not to use short tags since they only exist for backwards compatibility. They're deprecated. – Jeffrey Jan 01 '13 at 23:16
  • 1
    @ArtaexMedia: http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use. While the short tags `<%` and `` may be deprecated (because they conflict with XML templating engines), `=` most certainly is not. – mellamokb Jan 01 '13 at 23:23
2

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

PhearOfRayne
  • 4,990
  • 3
  • 31
  • 44
  • I think thats cleaner, for other stuff. Much cleaner and more manageable. That is kind of what I was expecting, but didnt know how to do. Thankyou @Steven Farley – 422 Jan 01 '13 at 23:19