PHP Random collection of element from an array

We can randomly collect one or more element from an array by using array_rand() function in PHP. We can specify the number of random elements required by specifying an optional parameter in side the function.
$value=array("Rabin","Reid","Cris","KVJ","John");

$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
We can create a six digit random number generator which will give us only characters.

srand ((double) microtime() * 10000000);
$input = array ("A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q",
"R","S","T","U","V","W","X","Y","Z"); $rand_index = array_rand($input,6); print $input[$rand_index[3]]; print $input[$rand_index[5]]; print $input[$rand_index[4]]; print $input[$rand_index[2]]; print $input[$rand_index[1]]; print $input[$rand_index[0]];
By using above code we can generate 6 digit random number of only characters. You can read how to generate random numbers here.

Example 1: Selecting One Random Element

<?php
$names = array("Alice", "Bob", "Charlie", "David");
$random_key = array_rand($names);
echo $names[$random_key];  // Outputs a random name
?>

Example 2: Selecting Multiple Random Elements

<?php
$names = array("Alice", "Bob", "Charlie", "David");
$random_keys = array_rand($names, 2);
echo $names[$random_keys[0]] . ", " . $names[$random_keys[1]];  // Outputs two random names
?>

Example 3: Randomly Selecting Keys from an Associative Array

<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$random_key = array_rand($fruits);
echo "$random_key => " . $fruits[$random_key];  // Outputs a random key and value
?>

Example 4: Selecting Multiple Keys and Displaying Keys and Values

<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$random_keys = array_rand($fruits, 2);
foreach ($random_keys as $key) {
    echo "$key => " . $fruits[$key] . "<br>";
}
?>

Read here how to generate random password string having alphabets and digits
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    gab

    21-02-2015

    Very nice script




    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer