How to get a random value from a PHP array? Explain with example?

Posted by

In php, we can get a random value from an array with this function “array_rand()”. this is an inbuilt function in php which is used to fetch a random number of elements from an array.

This function accepts two parameters $array and $num. The $array variable store the array elements and $num parameter holds the number of elements need to fetch. By default value of this parameter is 1.

syntax

array_rand( $array, $num )

example

<?php
 

$color = array( "yellow","red","orange","black","white","blue","pink");
 

  $rcolor = array_rand( $color, 2 );

  echo "<pre>";
  print_r($rcolor);
  echo "</pre>";
  
  echo $color[$rcolor[0]]. "<br>";
  echo $color[$rcolor[1]]
 ?>

output

Array
(
    [0] => 5
    [1] => 6
)
blue
pink
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x