Ben is a lifelong Nintendo fan who likes to build websites, and make video games. He buys way too much Lego.
When I was making my generative art I needed to generate a lot of random things. The simplest way to do that with PHP is to use the
rand() function selects a random integer between 0 and
getrandmax(), or 2 values if you supply them (eg
rand( 100, 200 )). This function is really useful, but on it’s own it has slightly predictable results. In this article I wanted to cover some of the other techniques I use to generate randomness with PHP.
To generate certain elements of the Iso City I would store information in an array, shuffle the contents, and then use the first item in the array. This is a nice simple method for picking a random item from an array. You could also pick a random number between 0 and the array size and use that as the index, but I like the simplicity of shuffle.
Using arrays and shuffle() I can also do weighted selections. By this I mean that if I want one result to appear more frequently than another then I can add it to the array more times than the other. Then select from the shuffled array in the same way.
I could probably write a function for generating the weighted list for me but I like to keep things simple so use something like this example:
Weighted Random Numbers
With rand or random there is a linear distribution between the start and end values. To makes things a bit less consistent I use a weighted random number function.
With this function I can generate random numbers that are weighted towards the lower value. The pow value can be tweaked to adjust the weighting. The higher the number, the further it is skewed to the bottom, the lower the number the smoother the curve.
This is a simple little tip, but sometimes I want to make something happen with a certain frequency – so I use a one line conditional to decide whether to run the code or not.
In this article I’ve listed a selection of the ways that you can use random numbers in PHP, but I’m sure there are many more techniques. It’s been interesting trying these different methods whilst creating the artworks and seeing how the needs and use change based upon where I am using them.
One thing I’ve not used is random seeds, which would allow me to make reproducable artworks by using the same random numbers each time. I think this would be interesting for creating individual things for specific people using things like email addresses as keys.