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 Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or 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

Add a Patch

Pull Requests

Add a Pull Request

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: Sat May 18 11:01:34 2024 UTC