The problem is that you go to the next $i
value even if when you just had a duplicate pick, meaning you will not always get to your total of 5 values.
But instead of fixing that, I would suggest to not try and try until you get a non-used value, but to remove values once you have picked them, so they cannot be picked again.
This you can do by first taking a temporary copy of your original array, and removing the elements (using array_splice) as you pick them so that in the next iteration they are no longer available for picking:
$temp = $col_ranges['B'];
for ($i=1; $i < 6; $i++) {
$col_B[] = array_splice($temp, rand ( 0 , count($temp)-1 ), 1)[0];
}
Note that the range of values given to rand
is decreased every time (count
becomes smaller as the array becomes shortened by the array_splice
).
This is more efficient as you know for sure the loop will only iterate 5 times and never more.
Alternative
An interesting alternative is using the shuffle
and array_slice
functions, again using a copy of the original array. This way you don't need the loop at all:
$col_B = $col_ranges['B'];
shuffle($col_B); // randomise the array
$col_B = array_slice($col_B, 0, 5); // keep only first 5