php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #67233 5.5.12 array rand is not random
Submitted: 2014-05-08 09:05 UTC Modified: 2014-05-08 14:18 UTC
Votes:1
Avg. Score:2.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: bugsphp077 at nabialek dot org Assigned:
Status: Duplicate Package: Arrays related
PHP Version: 5.5.12 OS: Windows 8.1
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: bugsphp077 at nabialek dot org
New email:
PHP Version: OS:

 

 [2014-05-08 09:05 UTC] bugsphp077 at nabialek dot org
Description:
------------
---
From manual page: http://www.php.net/function.array-rand
---


Function array_rand does not choose random value. In documentation there is info that there's no need to use srand or mt_srand any more. In fact using srand function before launching randTest function (in test script) solve this issue. However using mt_srand function (both with and without seed) doesn't solve this issue

Test script:
---------------
<?php
    $letters = array('a','b','c','d','e','f','g','h');
    $array = array();    
    // mt_rand used just for filling array, it may be filled manually if neccessary
    for ($i=0; $i< 200; ++$i) {
        $array[] = $letters[mt_rand(0,count($letters)-1)];                
    }    
    for ($i=0; $i< 10000; ++$i) {
        echo randTest($array)."<br />";                
    }    
    function randTest($array) {    
        $out = array();        
        while (count($array) > 0) {
            $index = array_rand($array,1);
            $out[] = $array[$index];
            unset($array[$index]);                        
        }        
        return implode('', $out);
    }

Expected result:
----------------
All lines should be random or at least no visible pattern of repetition should be possible to find

Actual result:
--------------
It repeats its results in test script each 14 times. I mean in output line 1 is the same as line 14, line 2 is the same as line 15, line 3 is the same as line 16 so it means it is not random at all.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-05-08 14:18 UTC] levim@php.net
-Status: Open +Status: Duplicate
 [2014-05-08 14:18 UTC] levim@php.net
This is well known, but sadly undocumented. Here's a bug report from 2001: https://bugs.php.net/bug.php?id=12312

It also appears to be more severe on Windows: https://bugs.php.net/bug.php?id=45301

I'm closing this as a duplicate of the latter bug.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 06:01:29 2024 UTC