# How to Generate a Random Integer using the rand() Function in PHP

Contents

In this article, you will learn how to generate a random integer using the rand() function in PHP.

## PHP rand() Function

PHP provides a random number generating function called rand( ), and you can use this function to generate random numbers.

For example, running the rand() function once produces the number “1243”, and running it a second time produces another number, such as “4312”.

## Usage

### Generate random numbers

If you run the rand function without specifying an argument, it returns a number greater than or equal to 0 and less than or equal to the maximum random number.

The maximum random number seems to vary depending on the execution environment.

Syntax:

`rand()`

### Generate the random number by specifying a range

If you set the argument of the rand function from `n`

to `m`

and execute it, a random number will be generated in the range from `n`

to `m`

.

Syntax:

`rand(n,m)`

n: Specifies the smallest integer to return (default is 0).

m: specifies the largest integer to return (default is getrandmax()).

### Generate odd or even random numbers

You can generate even or odd random numbers by doing the following.

Syntax:

```
rand(n,m)*2 // even number
rand(n , m)*2－1 // odd number
```