Math Functions in PHP: Part 7

Introduction

The PHP math function is used to handle values within the range of integer and float types. In this article I am describe the PHP math functions mt_rand, mt_srand and pi. To learn about other math functions, go to:

  1. Math Function in PHP:Part 1
  2. Math Functions in PHP:Part 2 
  3. Math Functions in PHP:Part 3 
  4. Math Functions in PHP: Part 4
  5. Math Functions in PHP: Part 5 
  6. Math Functions in PHP: Part 6
PHP mt_rand function

The PHP math mt_rand function returns a random integer using the Mersenne Twister algorithm.

Syntax
mt_rand (min , max)


Parameters in
mt_rand function

It is takes two parameters; they are:
 

Parameter Description
min It specifies a number.
max It specifies numbers (but it greater than the previous one (min) ).

Example of mt_rand function

The following sample of the mt_rand function is used to return a random integer.

<?php

$val1=mt_rand();

$val2=mt_rand(20,80);

$val3=mt_rand();

echo "Value of <b>mt_rand()</b> = <b>$val1</b> <br />";

echo "Value of <b>mt_rand(20.80)</b>=<b>$val2</b> <br />";

echo "Value of <b>mt_rand()</b> = <b>$val3</b> <br />";

?>

Output

math-mt-rand-function-in-php.jpg

PHP mt_srand function

The PHP math mt_srand function seeds the random number generator with a seed or with a random value if no seed is given.

Syntax

mt_srand (number)


Parameters in
mt_srand function

It is takes one parameter; it is:
 

Parameter Description
number It specifies an optional seed value.

Example of mt_srand function

<?php

function make_seed()

{

list($usec, $sec) = explode(' ', microtime());

return (float) $sec + ((float) $usec * 100);

}

mt_srand(make_seed());

echo mt_rand();

?>

Output

math-mt-srand-function-in-php.jpg

PHP pi function

The PHP math pi function returns the value of PI.

Syntax

pi ()

Example of pi function

<?php

$val=pi();

echo "Value of pi() function is  <b> $val</b>";

?>

Output

math-pi-function-in-php.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all