php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #26290 array_rand() not random
Submitted: 2003-11-17 12:00 UTC Modified: 2003-11-17 14:25 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: alisovoi at hotmail dot com Assigned:
Status: Not a bug Package: Performance problem
PHP Version: 4.3.4 OS: Linux Redhat 9
Private report: No CVE-ID: None
 [2003-11-17 12:00 UTC] alisovoi at hotmail dot com
Description:
------------
$array[array_rand($array)] is always the same element of the array. 
The server uses php.ini-recommended for the configuration.
(In PHP 4.3.2, this problem is non-existant. PHP 4.3.4 has this bug)

Reproduce code:
---------------
<?php
$random_sayings = array('Hey, this is not','randomly chosen','elements from an array');
echo($random_sayings[array_rand($random_sayings)]);
?>

Expected result:
----------------
Either one of the 3 elements of the array.

Actual result:
--------------
The same element no matter how many times the user refreshes.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-11-17 12:26 UTC] scottm at spamcop dot net
Can't confirm under same OS. I used a easier test case.

-----
<?php
$random_sayings = array('Hey, this is not','randomly chosen','elements from an array');
$i = 0;
echo '<pre>';
while ($i < 1000)
{
	print $random_sayings[array_rand($random_sayings)] . "\n";
	++$i;
}
echo '</pre>';
?>
 [2003-11-17 14:12 UTC] iliaa@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

You forgot to call srand() to generate random key. Hence the lack of random data.
 [2003-11-17 14:19 UTC] scottm at spamcop dot net
From the array_rand documentation
-----------
As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
 [2003-11-17 14:25 UTC] iliaa@php.net
Incorrect documentaion I'm afraid.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 20:01:28 2024 UTC