Using PHP for random, non-repeating numbers
Need a series of non-repeating but random numbers? For example, random images from a gallery or portfolio screenshots? Let me save you some time:
$numbers = range($min, $max);
shuffle($numbers);
$random_1 = $numbers[0]; // first random number
$random_2 = $numbers[1]; // next random, non repeating
$random_3 = $numbers[2]; // next random, non repeating
Normally I wouldn’t blog about something like that, except that I just spent 20 minutes using rand() to generate a random number, then saved it into an array, then ran an in_array() to look for it, and start the process over.
It wasn’t until I was about 15 minutes into it that I thought to myself… “What on Earth am I doing?”. Then stubbornness kicked in and I tried to finish my monstrosity, then I finally re-evaluated my strategy.
Funny, because I’ve never used shuffle() before for anything, so my brain could only think of commonly used array functions like sort() and asort() (and of course, your favourite and mine… array_intersect_uassoc() - which I freely admit to only just now looking up to discover it exists).
Why are we sometimes driven to code the most complex solution possible, and worse, even when we know it is utterly involved and inelegant, we still drive to make it work, “just to see it working”?

Richard wrote on
..very handy as I was just about to do the same thing!
Also, I downloaded a copy of Bambooinvoice (I am using CI for a few projects, so thought I might get some inspiration) and was surprised to see an (int) cast used. I use casting myself (having used it in C) but I’ve never seen it in another php programme.
I wonder why more people don’t use it?