Home > database >  Exclude elections from array_rand
Exclude elections from array_rand

Time:12-02

I found this php code which generates randomdly selects a value between 1 and 9, but excludes those in the array $exclude. IT WORKS.

$exclude = array(1,2,3);
while(in_array(($x = rand(1,9)), $exclude));
echo $x;

Now I want to select one of the letters in the array $items (from 'a' to 'h'), but excluding those in $exclude (from 'a' to 'c'). I use the following code:

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");
$rkey = array_rand($items);
while(in_array(($election = $items[$rkey]), $exclude));
echo $election;

PROBLEM: This works, but after refreshing a number of times, the browser stops working and keeps loading indefinitely. It does not display any error.

CodePudding user response:

Or a simpler way to do this is to use the inbuilt PHP function named array_diff() which returns a new list of items by removing (returning difference) existing items from the main list, as:

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");

$nItems = array_diff($items, $exclude);
$rkey = array_rand($nItems);

$election = $nItems[$rkey];

CodePudding user response:

$rkey is only evaluated once. You can substitute the code into the while loop:

<?php

$items = array("a", "b", "c", "d", "e", "f", "g", "h");
$exclude = array("a", "b", "c");
while(in_array(($election = $items[array_rand($items)]), $exclude));
echo $election;

Teh Playground!

Note that PHP has the array_diff inbuilt function which does the same thing.

$arrDiff=array_diff($items,$exclude);
echo $arrDiff[array_rand($arrDiff)];
  • Related