php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64167 Recursive function using mt_rand sometimes returns NULL
Submitted: 2013-02-07 02:45 UTC Modified: 2013-02-07 07:41 UTC
From: martin at psinas dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.4.11 OS: linux mint
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: martin at psinas dot com
New email:
PHP Version: OS:

 

 [2013-02-07 02:45 UTC] martin at psinas dot com
Description:
------------
Variable is properly set but returns as NULL value

Test script:
---------------
<?php

function mtrand_except($min, $max, $except) {
    $random_number = mt_rand($min, $max);
    if(!in_array($random_number, $except)) {
        echo $random_number.'<br />';
        return $random_number;
    }
    mtrand_except($min, $max, $except);
}

$random_arr = array();
for($i=1; $i<=90; $i++) {
    $rand = mtrand_except(1, 90, $random_arr);
    echo $i.'<br />'.$rand.'<hr />';
    $random_arr[] = $rand;
}

Expected result:
----------------
60
1
60
------
19
2
19
------
57
3
57
------
etc...

Actual result:
--------------
60
1
60
------
19
2
NULL
------
57
3
57
------
etc...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-02-07 07:41 UTC] nikic@php.net
You are missing a return statement before the recursive mtrand_except call ;)

Corrected version: http://codepad.viper-7.com/I0zgc5
 [2013-02-07 07:41 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Dec 27 02:01:29 2024 UTC