Skip to content

Commit 0cb6a31

Browse files
author
Jeroen van Wolffelaar
committed
Fix array_rand and array_suffle to use php_rand correctly
1 parent b0300e2 commit 0cb6a31

File tree

1 file changed

+6
-16
lines changed

1 file changed

+6
-16
lines changed

ext/standard/array.c

+6-16
Original file line numberDiff line numberDiff line change
@@ -1377,7 +1377,7 @@ PHP_FUNCTION(range)
13771377

13781378

13791379
static int array_data_shuffle(const void *a, const void*b) {
1380-
return (php_rand() % 2) ? 1 : -1;
1380+
return php_rand_range(0,1) ? 1 : -1;
13811381
}
13821382

13831383

@@ -2716,18 +2716,18 @@ PHP_FUNCTION(array_multisort)
27162716

27172717
/* {{{ proto mixed array_rand(array input [, int num_req])
27182718
Return key/keys for random entry/entries in the array */
2719+
2720+
/* FIXME:The algorithm used is bogus! */
27192721
PHP_FUNCTION(array_rand)
27202722
{
27212723
zval **input, **num_req;
2722-
long randval;
2724+
double randval;
27232725
int num_req_val, num_avail, key_type;
27242726
char *string_key;
27252727
uint string_key_len;
27262728
ulong num_key;
27272729
HashPosition pos;
27282730

2729-
php_error(E_ERROR, "Function array_rand temporarily disabled");
2730-
27312731
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 2 ||
27322732
zend_get_parameters_ex(ZEND_NUM_ARGS(), &input, &num_req) == FAILURE) {
27332733
WRONG_PARAM_COUNT;
@@ -2760,20 +2760,10 @@ PHP_FUNCTION(array_rand)
27602760
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(input), &pos);
27612761
while (num_req_val && (key_type = zend_hash_get_current_key_ex(Z_ARRVAL_PP(input), &string_key, &string_key_len, &num_key, 0, &pos)) != HASH_KEY_NON_EXISTANT) {
27622762

2763-
#ifdef HAVE_RANDOM
2764-
randval = random();
2765-
#else
2766-
#ifdef HAVE_LRAND48
2767-
randval = lrand48();
2768-
#else
2769-
randval = rand();
2770-
#endif
2771-
#endif
27722763

2773-
/* TEMPORARY HACK TO GET IT COMPILE */
2774-
#define PHP_RAND_MAX 1
27752764

2776-
if ((double)(randval/(PHP_RAND_MAX+1.0)) < (double)num_req_val/(double)num_avail) {
2765+
randval = php_drand();
2766+
if (randval < (double)num_req_val/(double)num_avail) {
27772767
/* If we are returning a single result, just do it. */
27782768
if (Z_TYPE_P(return_value) != IS_ARRAY) {
27792769
if (key_type == HASH_KEY_IS_STRING) {

0 commit comments

Comments
 (0)