PHP rand function (or not so rand)
- by Badr Hari
I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used:
<?php
header('Content-Type: image/png');
$lenght = 512;
$im = imagecreatetruecolor($lenght, $lenght);
$blue = imagecolorallocate($im, 0, 255, 255);
for ($y = 0; $y < $lenght; $y++) {
for ($x = 0; $x < $lenght; $x++) {
if (rand(0,1) == 0) {
imagesetpixel($im, $x, $y, $blue);
}
}
}
imagepng($im);
imagedestroy($im);
?>
My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers?
512:
513:
Edit: I'm running xampp on Windows to test it.