PHP - English

Get a Random Key from a PHP Array

<?PHP

 

You can grab a random key from an array. This could be useful in games of
chance. Here’s a simple script that simulates a single dice throw:

<?PHP

$numbers = array(1 => 1, 2 => 2, 3 =>
3, 4 => 4, 5 => 5, 6 => 6);
$random_key = array_rand($numbers, 1);
print $random_key;

?>

The function that returns the random key is this:

array_rand($numbers, 1);

You start off with the function array_rand( ). In between the round brackets,
you need two things: the name of your array, and how many random keys you
want to grab.

Try the script out. Refresh the page and you should see a different number
between 1 and 6 display.

In the next part, we’ll see how the count function
works when applied to an array.

.medrectangle-1-multi-102{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:2px!important;margin-left:0!important;margin-right:0!important;margin-top:2px!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

|

Kaynak : https://www.homeandlearn.co.uk/php/php6p7.html ‘sitesinden alıntı

Yorum Yap