Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regain constant pseudo-random in PHP 5.2

Tags:

php

random

I am including the same "random.inc" in foo.php and bar.php. For each, I want reproducible "random" results.

So in foo.php I always want one set of numbers and/or keywords. In bar.php another. Which shouldn't change on reload. That's what I mean by contant pseudo-random. And that's why I seeding on the url. However I still get different results for individual numbers as well as for array pickson every reload. This is the full php file:

<?
    header('Content-Type: text/plain');
    $seed = crc32( $_SERVER['REQUEST_URI'] );
    echo "phpversion: ".phpversion()."\nseed: $seed\n";
    srand( $seed ); // (seed verified to be contant as expected)

    // neither single values nor array pics turn out deterministic
    echo ''.rand(0,100).' '.rand(0,100).' '.rand(0,100)."\n";
    $values = array( '0'=>21,'1'=>89,'2'=>96,'3'=>47,'4'=>88 );
    print_r( array_rand( $values, 3 ) );
?>

In the days of PHP4.1 it was (verified) possible to achieve constant pseudo-random like this. array_rand API documentation describes as a feature that since 4.2 initialization happens automatically. Perhaps this is overriding any explicit seeding? (if so, perhaps explicit seeding should raise an internal PHP flag, preventing automatic seeding?). Btw: mt_srand() and srand() are equally not working.

I would really like to get my deterministic / constant pseudo-random back...

Update: Solution below (Windows and/or version 5.2 's fault)

like image 601
Frank Nocke Avatar asked Apr 25 '26 19:04

Frank Nocke


1 Answers

Works for me (PHP/5.3.6):

<?php

$data = range(1, 100);
srand(1);
print_r(array_rand($data, 3));

... always prints:

Array
(
    [0] => 21
    [1] => 89
    [2] => 95
)

... in my machine. Apparently, the exact numbers differ depending on the exact environment but they're reproducible.

like image 142
Álvaro González Avatar answered Apr 27 '26 09:04

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!