2

Example: I have an array with 3 values:

0 = 1
1 = 4
2 = 5

I want to get a random number like

$random = rand(1, 5);

But I need to get a number that is different from the array values. I need it to return 2 or 3.

5
  • So you have a range from where you want to get a random number, but without numbers from your array, right? Also have you tried something? Commented Apr 9, 2015 at 21:54
  • So do { $random = rand(1, 5); } while (in_array($random, $myArray)); Commented Apr 9, 2015 at 21:54
  • Thanks for the answer! It worked but I'm getting a Fatal Error sometimes: Fatal error: Maximum execution time of 30 seconds exceeded Commented Apr 9, 2015 at 22:00
  • @Rockman Have you read my first comment^ ? Commented Apr 9, 2015 at 22:03
  • You're excluding most of the possible random numbers. So sometimes it can take many tries before it picks one that's allowed. Commented Apr 9, 2015 at 22:03

1 Answer 1

2

This should work for you:

(Here I create the range from where you get your random number with range(). Then I get rid of these numbers which you don't want with array_diff(). And at the end you can simply use array_rand() to get a random key/number)

<?php

    $blacklist = [1, 4, 5];
    $range = range(1, 5);
    $randomArray = array_diff($range, $blacklist);
    echo $randomArray[array_rand($randomArray, 1)];

?>

output:

2 or 3

EDIT:

Just did some benchmarks and the method with the loop is much slower than the code above!

I created an array(blacklist) from 1...100'000 and a random number array from 1... 100'001.

So that script should only create one/unique random number. With the loop method you get an error:

Fatal error: Maximum execution time of 30 seconds exceeded

And with the posted code above it takes 1.5 sec in average.

Sign up to request clarification or add additional context in comments.

6 Comments

This is much nicer than the loop, it shouldn't cause a time exceeded error.
@Barmar Thanks, That's why I posted it when I saw the possible dupe, since there were no such answer.
@Barmar Just did some benchmarks and it's a huge difference! (see updated answer)
@Rizier123 Thanks again! It worked just fine, and it is really what i was looking for. I didn't know this array_diff.
I accepted now, I guess... This was my first question here in stackoverflow, i'm still learning how to use it, hehe.
|

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.