Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a loop where I am inserting some html element and I need to add a class to it but I need this class to be from 1 to 4 max, like gallery__item--3 or gallery__item--1 and applied randomly without duplicates and avoid gallery__item--3 and gallery__item--3.

Currently I do the following but I get duplicates and I am not sure how to check:

$min = 1;
$max = 4;
foreach( $galleria as $image ):  
  <figure class="gallery__item--<?php echo rand($min,$max); ?>">
endforeach;

Literally looking for:

1,3,4,2 or 4,2,1,3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since you want to avoid duplicates, I assume there are only four images.

You can use shuffle to randomize a previously created array:

$rands = range(1,4);
shuffle($rands);
foreach( $galleria as $image ):  
  <figure class="gallery__item--<?= array_pop($rands); ?>">
endforeach;

If you have more than 4 elements you can still use this approach checking if there are elements left and regenerating the array. If you need every iteration to be different you can also check that the ordering hasn't been used before (just keep in mind that there are a limited number of combinations).

$rands = [];
$pasts = [];

foreach( $galleria as $image ):  
    if (empty($rands)):
        do {
            $rands = range(1,4);
            shuffle($rands);
        } while (in_array($rands, $pasts)); 
        $pasts[] = $rands;
    endif;
    <figure class="gallery__item--<?= array_pop($rands); ?>">
endforeach;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...