PHP | srand( ) Function

Many times while designing questions or algorithms we require to generate random numbers. We already have studied a built-in function in PHP for generating random numbers in the article PHP |rand() Function. The rand() function is used in to generate random numbers. If we generate a sequence of random numbers with rand() function, it will create the same sequence, again and again, every time the program runs. To solve this issue another built-in function of PHP, srand() can be used.

The srand() function in PHP is used to seed the random number generator rand(). The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at program start. The srand() function seeds the random number generator with seed(arg) or with a random value if no seed(arg) is given.

Syntax:



srand($seed)

Parameters: This function accepts a single parameter seed. It is an optional parameter and is of integer type. It specifies the seed value.

Return Value: This function does not returns any value.

Examples:

Input : srand(time());
Output : 1793542495

Input : srand(5)
Output : 3

Below programs illustrate the srand() function in PHP:

  1. When timestamp is used as the $seed value along with srand() function:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    srand(time());
      
    echo(rand());
      
    ?>

    chevron_right

    
    

    Output:

    1793542495
  2. When a user-defined seed value is passed as an argumnet with srand() function:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    srand(5); 
      
    echo(rand(1, 10)); 
      
    ?>

    chevron_right

    
    

    Output:

    3

Important Points To Note:

  • srand() function can be used to generate random numbers.
  • srand() function doesn\’t create the same sequence of random numbers like the rand() function.
  • It doesn’t have a return value.

References:
http://php.net/manual/en/function.srand.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.