Selecting a letter from random group of array for registered user in php


Keywords:php 


Question: 

The problem is I have two groups say A and B which I have predefined in an array like

$random_groups = [B,A,A,B,A,A,B,B,A,A,B,B,B,A,A,B,A,B,B,A,A,A,B,B,A,B,B,B,A,A,A,B,B,A,B,A,A,B,B,B,A,A,A,B,B,A,A,B,A,B,A,B,B,A,B,A,B,A,A,B,B,A,B,A,B,A,B,A,A,B,A,B,B,B,A,A,B,A,B,A...]

and when user submits a form he should get B from the above array if he is the first person to register after I apply this logic and if second person registers he should get A, if third he should get A and so on.

I am so confused to have to work around this logic. I tried a few options but didn't got the result properly.


1 Answer: 

<?php
    $random_groups = array('B','A','A','B','B','A','A','B','A','B','B','A','A','B','A','A','B','B','A','B','A','B','B','A','A','B','A','B','B','A','B',
                      'A','B','A','B','A','A','B','A','B','B','A','A','B','A','A','B','B','A','A','B','B',
                      'B','A','A','B','A','B','B','A','A','A','B','B','A'); //IF THOSE ARE STRINGS YOU SHOULD ADD quotations (YOUR PATTERN)
    $rank_reg = 201; //EXAMPLE IF HE IS 201 REGISTERED

    do{
        array_push($random_groups,'B','A','A','B','B','A','A','B','A','B','B','A','A','B','A','A','B','B','A','B','A','B','B','A','A','B','A','B','B','A','B',
                      'A','B','A','B','A','A','B','A','B','B','A','A','B','A','A','B','B','A','A','B','B',
                      'B','A','A','B','A','B','B','A','A','A','B','B','A');
        }while($rank_reg -1 > count($random_groups)); // THIS CODE WILL ADD YOUR PATTERN TO THE END OF THE ARRAY WHILE THE RANK EXCEEDS THE INDEX OF YOUR ARRAY
       
    foreach($random_groups as $index => $output):
       if(($rank_reg - 1) == $index): // ADDED A COMPUTATION OF -1 BECAUSE ARRAYS STARTS AT 0
        echo $output;
       endif;
        continue; //IF RANK IS NOT MATCH TO AVAILABLE GROUPS
    endforeach;
?>