Get random value from multidimensional array PHP?

Get random value from multidimensional array PHP?

This is a tricky one.

But you can use this improvised code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$array_limit = array();
array_push($array_limit, array("a", "a2"));
array_push($array_limit, array("b", "b2"));
 
$random = rand(0, 1);
$i = 0;
foreach ($array_limit as $result){
	if ($i == $random){ 
	echo $result[0].'-'.$result[1];
	}
	$i++;
}
?>

This will echo either a-a2 or b-b2, basically the values from a random array

The trick and improvisation was to use $i++.
$random will generate either 0 or 1.
Then $i checks if it’s 0 or 1 and only display the entries from the array 0 or 1.

If you have any questions, please leave in the comments.

Add a comment: