Like the question says I am working with the
array_rand
function in php and my goal is to get this function to randomly generate a class in my loop. Currently it just prints the 2nd value in the array each time. How can I have this echo a random class for the div in my loop?if ($featured_query->have_posts()) :
while ($featured_query->have_posts()) :
$featured_query->the_post();
$masonry_classes = array(
'grid-item',
'grid-item--width2'
);
$random_class = array_rand($masonry_classes, 2);
?>
<li <?php //post_class( $classes ); ?> class="<?php echo $masonry_classes[$random_class[1]]; ?>">
Answer:
since you only want one array element you can combine the (random)selection and display on to a convenient one-liner:
echo $masonry_classes[array_rand($masonry_classes)];
ref: array_rand()
It looks like you misunderstood how
array_rand
works.
If you don't specify the second parameter or set it to
1
, the function will return an integer which is an index of the random entry in the array.
If you set the second parameter to a number greater than
1
then the function will return an array of randomly picked indexes.
So, if you do:
$rand = array_rand($masonry_classes);
...you will end up with with either
0
or 1
(because your array contains two entries whose indexes are 0
and 1
respectively). In that case you can do$class = $masonry_classes[array_rand($masonry_classes)];
to retrieve one random class and the following to print it:
class="<?php print $class; ?>"
If you do
$rand = array_rand($masonry_classes, 2);
then it will return 2 random indexes which in your case are both,
0
and 1
.
To retrieve the matching entries you'll now have to do the following:
$classes = array_intersect_key($masonry_classes, array_flip($rand));
To render them in your HTML simply do the following join:
class="<?php print join(' ', $classes); ?>"
No comments:
Post a Comment