PHP lcg_value() Function

The lcg_value() function generates a pseudo-random floating-point number between 0 and 1. LCG stands for Linear Congruential Generator, which is one of the oldest and most widely used pseudorandom number generator algorithms.

Syntax

lcg_value(): float

Parameters

This function takes no parameters.

Return Value

Returns a pseudo-random float value between 0.0 and 1.0 (inclusive of 0.0, exclusive of 1.0).

Example

Here's a basic example demonstrating the lcg_value() function ?

<?php
    echo "Random value 1: " . lcg_value() . "<br>";
    echo "Random value 2: " . lcg_value() . "<br>";
    echo "Random value 3: " . lcg_value();
?>

The output will be different each time the script runs ?

Random value 1: 0.45920201711279
Random value 2: 0.18118693614628
Random value 3: 0.73829482746193

Generating Random Numbers in Ranges

You can scale the output to generate random numbers within specific ranges ?

<?php
    // Generate random integer between 1-100
    $randomInt = (int)(lcg_value() * 100) + 1;
    echo "Random integer (1-100): " . $randomInt . "<br>";
    
    // Generate random float between 5.0-15.0
    $min = 5.0;
    $max = 15.0;
    $randomFloat = $min + (lcg_value() * ($max - $min));
    echo "Random float (5.0-15.0): " . round($randomFloat, 2);
?>
Random integer (1-100): 46
Random float (5.0-15.0): 6.81

Conclusion

The lcg_value() function provides a simple way to generate pseudo-random numbers between 0 and 1. While suitable for basic randomization needs, consider using random_int() or random_bytes() for cryptographically secure applications.

Updated on: 2026-03-15T08:57:33+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements