Shuffling String Number and Array in PHP

Shuffling String Number and Array in PHP

Hello friends, welcome to my today’s post in PHP. Today we are going to learn how to shuffle string, number and array in PHP. Shuffling is very useful while you are working in a trivia games or examination management system or any puzzle game.

Let’s go for details –

1. Shuffle string using str_shuffle() Function:

For randomizing or shuffling characters in a word or a full sentence we can use str_shuffle function. str_shuffle function takes a string as an input and produce random string each time. You can also called it randomization function for string.

string str_shuffle ( string str )

– Write a live Example of str_shuffle function:

$str = 'coolajax.net';

$shuffled = str_shuffle($str); // This will echo something like: nca.tajaxlooe

echo $shuffled;

– Important notes about str_shuffle() function:

str_shuffle() shuffles a string. One permutation of all possible is created.

2. Shuffle number using rand() function:

rand() function useing for generating random integer numbers. It takes 2 parameter as input and produce a single random number. First parameter for starting number of range and second parameter use for ending point of range. If you don’t set them , then rand() function generate an arbitrary random number.

int rand($int min, $int max)

– Write a live example of rand() function:

// Example: 1

$random_number = rand(100,200);

echo $random_number; // Output: 155

// Example: 2

$random_number = rand();

echo $random_number; // Output: 4532

3. Shuffle array using shuffle() function:

Shuffle() function use for shuffling array items. This function takes an array as input and produce a new array with new index.

bool shuffle($array)

– Write a live example of shuffle() function:

$my_friends = array('0'=>"MAK", '1'=>"MIK", '2'=>"Xenious");


$shuffle_array = shuffle($my_friends);



Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Back To Top