user3892905
user3892905

Reputation: 396

Get random from one PHP array but not match from another

I have two arrays in PHP: big and small. All the values in small arrays are included in big array. I need to get random value from big array but it will be not matched with any value of small array. Something like:

$big = array('2','3','5','7','10');
$small = array('2','5','10');
$random = '3'; // it's not 2, 5 or 10

Upvotes: 1

Views: 207

Answers (3)

raidenace
raidenace

Reputation: 12836

$big = array('2','3','5','7','10');
$small = array('2','5','10');

$nums = array_diff($big,$small);//numbers in big that are not in small
$rand = array_rand($nums); //get a random key from that set
$val = $nums[$rand]; //get the value associated with that random key

Upvotes: 3

dognose
dognose

Reputation: 20909

You can use array_diff() to determine the difference - and pick a random number (using mt_rand()) from the resulting array:

$arrDiff = array_values(array_diff($big, $small));
$random = $arrDiff[mt_rand(0, count($arrDiff)-1)];

Note: the array_values() method makes sure that only the values are copied to the array $arrDiff, so the indexes from 0...n-1 are filled with values.array_diff() will maintain the index-positions, so there might be no index 0, 1 or whatever, as stated by @Undefined-Variable.

Upvotes: -1

Rodrigo
Rodrigo

Reputation: 3278

$bigs = ['1', '2', '3', '5', '10'];
    $small = ['1', '5', '10'];

    foreach($bigs as $big)
    {
        if(!in_array($big, $small))
        {
            echo $big. "\n";
        }
    }

Upvotes: 0

Related Questions