1

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.

Rockman
  • 35
  • 1
  • 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? – Rizier123 Apr 09 '15 at 21:54
  • So `do { $random = rand(1, 5); } while (in_array($random, $myArray));` – Mark Baker Apr 09 '15 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 – Rockman Apr 09 '15 at 22:00
  • @Rockman Have you read my first comment^ ? – Rizier123 Apr 09 '15 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. – Barmar Apr 09 '15 at 22:03

1 Answers1

1

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 1
    This is much nicer than the loop, it shouldn't cause a time exceeded error. – Barmar Apr 09 '15 at 22:09
  • @Barmar Thanks, That's why I posted it when I saw the possible dupe, since there were no such answer. – Rizier123 Apr 09 '15 at 22:10
  • @Barmar Just did some benchmarks and it's a huge difference! (see updated answer) – Rizier123 Apr 09 '15 at 22:19
  • @Rizier123 Thanks again! It worked just fine, and it is really what i was looking for. I didn't know this array_diff. – Rockman Apr 09 '15 at 22:19
  • I accepted now, I guess... This was my first question here in stackoverflow, i'm still learning how to use it, hehe. – Rockman Apr 09 '15 at 22:25
  • @Rockman no problem, enjoy your day :D (FYI: You can take a tour here: http://stackoverflow.com/tour and see a bit how this site works and where everything is) – Rizier123 Apr 09 '15 at 22:28