Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to get random value out of an array in PHP?



To get random value out of an array in PHP, the code is as follows−

Example

 Live Demo

<?php
   $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );
   echo "Array values ...
";    echo "Value 1 = " . $arr["p"], "
";    echo "Value 2 = " . $arr["q"], "
";    echo "Value 3 = " . $arr["r"], "
";    echo "Value 4 = " . $arr["s"], "
";    echo "Value 5 = " . $arr["t"], "
";    echo "Value 6 = " . $arr["u"], "
";    echo "Value 7 = " . $arr["v"], "
";    echo "Value 8 = " . $arr["w"], "
";    echo "Random value from arary = ".$arr[array_rand($arr)]; ?>

Output

This will produce the following output −

Array values ...
Value 1 = 150
Value 2 = 100
Value 3 = 120
Value 4 = 110
Value 5 = 115
Value 6 = 103
Value 7 = 105
Value 8 = 125
Random value from arary = 110

Example

Let us now see another example −

 Live Demo

<?php
   $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" );
   echo "Array values ...
";    echo "Value 1 = " . $arr["p"], "
";    echo "Value 2 = " . $arr["q"], "
";    echo "Value 3 = " . $arr["r"], "
";    echo "Value 4 = " . $arr["s"], "
";    echo "Value 5 = " . $arr["t"], "
";    echo "Value 6 = " . $arr["u"], "
";    echo "Value 7 = " . $arr["v"], "
";    echo "Value 8 = " . $arr["w"], "
";    $res = array_rand($arr, 2);    echo "Random values from array...";    echo $arr[$res[0]]." ".$arr[$res[1]]; ?>

Output

This will produce the following output−

Array values ...
Value 1 = 150
Value 2 = 100
Value 3 = 120
Value 4 = 110
Value 5 = 115
Value 6 = 103
Value 7 = 105
Value 8 = 125
Random values from array...150 115
Updated on: 2019-12-24T12:15:57+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements