php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50421 Inconsistent behavior in array_rand() after PHP 5.2.10 changes
Submitted: 2009-12-09 04:09 UTC Modified: 2009-12-09 18:28 UTC
From: v1d4l0k4 at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.11 OS: Ubuntu 9.10
Private report: No CVE-ID: None
 [2009-12-09 04:09 UTC] v1d4l0k4 at gmail dot com
Description:
------------
PHP 5.2.10 introduced a controversial BC break in array_rand() function that doesn't sort array values when the $num_req param is equal to array count.

This was the most incomprehensive change I've seen in the PHP development so far.

If I have a random $num_req between 1 and array count I'll need to check if I've to use array_rand() ou shuffle()? It seems so stupid...

On the other hand, if this change will remain it need to be fixed anyway: there's no sense in allow array count in $num_req - it returns the array unchanged with no warnings. In this case this parameter should receive a value less than the array count. And it should be nice to have shuffle() use recommendation in the warning if $num_req is equal to array count.

BTW, the manual notes about this array_rand() change is very very very incomprehensive.

Reproduce code:
---------------
<?php

$array = range('a', 'z');

foreach (array_rand($array, count($array)) as $key) {
    print $array[$key];
}

?>

Expected result:
----------------
MAYBE: frkzmnvuyiptdcsewbxgjqhloa

Actual result:
--------------
ALWAYS: abcdefghijklmnopqrstuvwxyz

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-12-09 08:24 UTC] jani@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


 [2009-12-09 08:26 UTC] jani@php.net
See bug #48224 for why this was done.
 [2009-12-09 18:28 UTC] v1d4l0k4 at gmail dot com
I already see the bug #48224. It was mainly for this that I wasted my time writing this. The current behavior is clearly bogus.

There's no sense to do this. It's not a fix, it's a feature removal. Even if this is definitive, I repeat: there's NO ABSOLUTE SENSE in accept array count in $num_req param.

Again: this was the most incomprehensive change I've seen so far (in the past 5 years) in the PHP development.

PS: The recomendation to check the incomprehensive array_rand() docs at manual was a joke, right?
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Dec 04 06:00:01 2025 UTC