1

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
3

3 Answers 3

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

4 Comments

"min/max" will work on the values, not on the keys. so, this will return a random between 3 and 7 - which is not what op wants, cause for instance "6" is possible but not part of any array.
Yes, @dognose is right, solution by raidenace doesn't work if $big = array('7','2','10','5','3'); i.e. digits of array has random order
@user3892905 - array_rand returns a random key from the array. In order to get the value you have to query using that random key like : $nums[$rand]. It doesnt have anything to do with random order of digits. I have updated answer just for clarity
for further reader: My prior comment refered to the first version of the post which has been updated.
0
$bigs = ['1', '2', '3', '5', '10'];
    $small = ['1', '5', '10'];

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

3 Comments

this just echos all the unique array values. also, under normal circumstances, \n will not break the line unless you send plaintext headers to the browser.
i just echoed it out so he could see the values being returned, I wouldn't actually return it like this @Adelphia
this is basically just a more complicated array_diff() anyways.
-1

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.

3 Comments

Is there a function called random() ?
There is an error in your answer - array_diff retains the key original key indices - thus if you randomly select a key index between 0 and count, it might not exist.
@UndefinedVariable valid point. Added array_values to fix that.

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.