Skip to content

srand(0) set random seed to 0 instead random #10292

Closed
@adic3x

Description

@adic3x

Description

The following code:

<?php
function foo(): int
{
	srand(0);
	$bar = rand(0, 1023);
	var_dump($bar);
	return $bar;
}

var_dump(foo() === foo());

Resulted in this output:

int(684)
int(684)
bool(true)

But I expected this output instead:

int(23)
int(756)
bool(false)

But this code:

<?php
function foo(): int
{
	srand();
	$bar = rand(0, 1023);
	var_dump($bar);
	return $bar;
}

var_dump(foo() === foo());

Works fine:

int(722)
int(132)
bool(false)

https://www.php.net/manual/en/function.srand.php

Seeds the random number generator with seed or with a random value if seed is 0.

It's seems like srand(0) process 0 as new seed value instead 0 must reset seed to new random value.

PHP Version

PHP 8.2.0

Operating System

Win 11 build 25272 (insider)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions