1

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);
?>
1
  • 1
    compare $rand_months with $alreadyin. If it's in, do array rand again. You can put it in a while loop that only exits when two uniques are generated. Commented Dec 18, 2018 at 19:49

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Abra but why I am getting associated array instead of name of months?
Because array_rand returns the keys, I was just using what you had.
Great answer. array_rand() returns random indices. You'll need to add a final step to index into the original array using each of the returned indices like $rand_months = array_map(function ($e) use ($months) { return $months[$e]; }, array_rand(array_diff($months, [$alreadyin]), 2));
but the output looks like [0] => 3 [1] => 8 instead of [0] => Mar [1] => Aug
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.