A PHP random array is an element that can be chosen with the help of the array_rand() function. Moreover, there is another function that shuffles the arrays by assigning new positions to the given elements. So, in this post, you’ll see how you can pick a random array element along with shuffling a particular array.

Bạn đang xem: Php random array: how to shuffle and select random elements

Read till the end to play with the arrays the same way you play different thẻ games.


PHP Array_rand: Explaining the Function’s BasicsHow to lớn Get Random Value from Array: Flip It FirstPHP Random Array Element: Targeting the KeysPHP Randomize Array: Using the Shuffle() Function:The Lucky Draw Program

PHP Array_rand: Explaining the Function’s Basics

The PHP array_rand function can be considered a technical spinner that returns one value out of many values. Actually, you can ask it khổng lồ return more than one random value as well. So, the said technical spinner accepts an array và an optional integer that represents the number of random elements that you want. Next, the PHP array_rand function will return either a single random key or an array of random keys depending on the đầu vào that you’ve passed lớn it.

Please feel miễn phí to follow this syntax: array_rand(array, count).

– Changes Made in the array_rand Function

In PHP 4.2, the random number generator has been already seededIn PHP 5.2.1, the resulting array preserves the original order of the keys while returning the random keysIn PHP 7.1.0, the libc rand function has been replaced by the Mersenne Twister Random Number Generator

– Example Code Block for Getting PHP Random Array Key

For example, let’s assume a situation in which you have an array of colors that suit best the purpose of your website. Chú ý that the keys are set to color names while the values contain the hashcodes of the corresponding colors. However, you can’t decide on any single color to set as the background màu sắc of your trang chủ page. So, if you find yourself in such a predicament, you’ll need to lớn trust the PHP array_rand function và pass the colors array to it by running the code block given below:

// creating an array of background colors$bg_colors = array(“dark blue” => “#00008B”,“black” => “#000000”,“sienna” => “#A0522D”,“saddle brown” => “#8B4513”,“navy blue” => “#000080”);// picking out a single random color$pick_one = array_rand($bg_colors);// printing the random colorecho “$pick_one ”;// output: navy blue// picking out two random colors$pick_two = array_rand($bg_colors, 2);// printing two random colorsprint_r($pick_two);// output: Array ( <0> => black <1> => sienna )?>

– Note:

The PHP array_rand function will return a different key every time you load the PHP script document.

How to Get Random Value from Array: Flip It First

Is it possible to get a random value from an array instead of a random key? Certainly, you can spin the wheel khổng lồ get some random values by using the array_flip() function before the PHP array_rand function. The stated step will ensure that the values of the given array have become keys before picking some random keys from the same.

Hence, the functionality of the array_rand doesn’t change. However, the input is adjusted to lớn bring out your preferred results.

– Example Code Block for Getting a PHP Random Array Value

Let’s take an instance where you have an array of flowers that contains the flower names as values và the flower colors as keys. Now, you want to select some random flower names to lớn display on the “services” page of your event planning website. So, here you’ll flip the flowers array and pass the flipped array khổng lồ the PHP array_rand function.

Please feel không tính tiền to use the given piece of code for getting random flower names every time you open your “services” page:

// creating an array of flowers$flowers = array(“peach” => “Rose”,“white” => “Daisy”,“yellow” => “Daffodil”,“purple” => “Iris”,“red” => “Anemone”,“pink” => “Buttercup”,“light pink” => “Lotus”,);// flipping the flowers array$flip_flowers = array_flip($flowers);// getting three random flowers$random_flowers = array_rand($flip_flowers, 3);// printing the flower names separated by spacesforeach($random_flowers as $flower)echo “$flower “;?>

The names of the flowers will be displayed lượt thích this:

Anemone Buttercup Lotus

PHP Random Array Element: Targeting the Keys

Don’t you want to lớn use the array_flip() function for getting random value from array? Then here is a solution that will satisfy this requirement of yours.

You can begin by using the array_rand() function. Afterward, you can get the corresponding value of the key returned by the PHP array_rand function by targeting the given key.

Xem thêm: Windows Apps For Real Time Strategy Game, Download Rts

However, if you’ve generated an array of random keys then you can iterate through your original array with the returned keys by using the foreach loop to lớn get your desired result.

– Coding Example to lớn PHP Randomly Select from Array

For instance let’s assume that you have an indexed array of coding languages and you want to lớn pick out only three random languages from it. Here, you’ll start by calling the array_rand function. Next, you’ll need khổng lồ use the foreach loop to iterate through the original array with random keys and get the corresponding values.

Please have a look at the code block that we have created for your use below that implements the array_rand function followed by a foreach loop:

// creating an array of languages$lang = array(“PHP”,”HTML”,”CSS”,”JavaScript”,”Python”,”C Sharp”,”Perl”);// using the array_rand function khổng lồ get three random keys$random = array_rand($lang,3);// iterating through the array of random keysfor($i = 0; $i // accessing the values of the random keysecho $lang<$random<$i>> . “”;}?>

Although the values may vary, the đầu ra will be shown like this:


PHP Randomize Array: Using the Shuffle() Function:

Well, you won’t need a long mô tả tìm kiếm to understand the functionality of the shuffle function as its name is clear enough. So, the shuffle() function is used to PHP randomize array by assigning new keys to lớn the elements. Similar khổng lồ the array_rand() function, the given function switched from the libc rand function khổng lồ the Mersenne Twister Random Number Generator in PHP 7.1.0.

– Workings of the Shuffle() Function

The shuffle() function accepts an array và assigns new keys to lớn the elements of the given array. Next, it returns true on success & false on failure.

Its syntax is as simple as the one given here: shuffle(array).

– Coding Example khổng lồ PHP Randomize Array By Using Shuffle()

Let’s take a case in which you might have created a system that asks for the lucky numbers of the users at the time of registration. Next, you would have added all the numbers in an array. However, now you want to shuffle the array of lucky numbers because you don’t want to reveal the order of the same. Hence, you’ll use the shuffle() function lớn PHP randomize array.

Here is a code block that will assist you in randomizing the above discussed array & printing the original và the shuffled array:

// creating an array of lucky numbers$lucky = array(1,4,2,8,0,7,6,9);// printing the array of lucky numbersprint_r($lucky);echo “”;// shuffling the arrayshuffle($lucky);// printing the shuffled arrayprint_r($lucky);?>

These are going to be the results:

Array ( <0> => 1 <1> => 4 <2> => 2 <3> => 8 <4> => 0 <5> => 7 <6> => 6 <7> => 9 )

Array ( <0> => 1 <1> => 0 <2> => 9 <3> => 4 <4> => 2 <5> => 8 <6> => 6 <7> => 7 )

The Lucky Draw Program

As now you know how khổng lồ get a random value from an array, here is something exciting for you: “The Lucky Draw Program.” So, go through the code representation below to create an incredible program based on the array_rand() function.

– Coding Example for Creating the Lucky Draw Program

// creating a multidimensional array for entries$draw = array(array(“xyz”,”City1″),array(“abc”,”City2″),array(“jkl”,”City3″),array(“ghi”,”City1″),array(“pqr”,”City2″),array(“mno”,”City5″));// getting a random entry$get = array_rand($draw);// printing the random entryprint_r($draw<$get>);// output: Array ( <0> => mno <1> => City5 )?>

Wrapping Up

Indeed, the array_rand function is enough to get a PHP random array element without writing many lines of code. Furthermore, some notable points are listed below khổng lồ help you in selecting random keys, random values, and shuffling arrays:

The PHP array_rand function helps in picking out a random key from an arrayThe PHP array_rand function accepts an array & the required number of random elementsA single random key or an array of random keys is returned by the array_rand functionYou can use the array_flip function before the array_rand function to get one or more random valuesYou can also get the random values by targeting the random keysYou can use the shuffle() function khổng lồ PHP randomize array

So, now you have got the right functions to create many other programs that require selecting PHP random array elements. Also, please feel free to use the code blocks given above to lớn have a better coding experience when you practice your skills.