Mona Coder
Mona Coder

Reputation: 6316

Select Two Unique Random From Array while Are not Equal to a Given Value

How can I select two unique random from and array and check that it are not equal with one pre-selected (default value)? For example I have an array of months like

 $months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

and a given month $alreadyin = "Feb"; now I need to select two unique months which are not equal to $alreadyin?

<?php
    $alreadyin = "Feb";
    $months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    $rand_months = array_rand($months, 2);
?>

Upvotes: 1

Views: 37

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Compute the difference (get months that are not $alreadyin) and then select 2 at random:

$rand_months = array_rand(array_diff($months, [$alreadyin]), 2);

You could also search for and remove $alreadyin:

unset($months[array_search($alreadyin, $months)]);
$rand_months = array_rand($months, 2);

array_rand returns random keys from the array, so you may need something like:

foreach($rand_months as $key) {
    echo $months[$key];
}

To get the actual month names using the first example, shuffle the array and slice 2:

$months = array_diff($months, [$alreadyin]);
shuffle($months);
$rand_months = array_slice($months, 0, 2);

Or using the second example:

unset($months[array_search($alreadyin, $months)]);
shuffle($months);
$rand_months = array_slice($months, 0, 2);

Upvotes: 4

Ibu
Ibu

Reputation: 43840

You can use this simple process. Get random values, check if they match, repeat if they don't.

function getUniqueMonth( $alreadyin ) {
    $months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    while( true ) {
        $rand_months = array_rand( $months, 2 );
        if ( !in_array( $alreadyin, $rand_months ) ) {
            return $rand_months;
        }
    }
}

You can always add a counter for safety, to make sure the computer doesn't keep looping forever.

Upvotes: 0

Related Questions