PHP str_shuffle() Function

What is PHP str_shuffle() Function?

If you want to randomly shuffle all the characters of string, use str_shuffle() function.

Syntax:

str_shuffle(string)

Parameters:

The Function has 1 parameter which is required-

string (Required): The string that the function shuffles.

Return Values:

The function returns a shuffled string.

Examples:

Example:

<?php
$string="password";
echo"Before shuffling, the string is: ".$string;
echo"<br />";
echo"After shuffling, the new shuffled string is: ".str_shuffle($string);
?>

Output:

Before shuffling, the string is: password
After shuffling, the new shuffled string is: ssodwpra

Explanation:

The function randomizes the characters and returns the output. Note, every time, you run this code, you’ll get a different output.

Practical Usages of str_shuffle() Function:

We can generate a random password from a set of rules with this function. Check the example below-

<?php
$string="aeiou0123$%&";
echo"Before shuffling, the string is: ".$string;
echo"<br />";
echo"After shuffling, the password is: ".str_shuffle($string);
?>

Output:

Before shuffling, the string is: aeiou0123$%&
After shuffling, the password is: 1uoia23%e0&$

Notes on str_shuffle() Function:

The function doesn’t modify the original string.

<?php
$string="password";
echo"Before shuffling, the string is: ".$string;
echo"<br />";
echo"After shuffling, the new shuffled string is: ".str_shuffle($string);
echo"<br />";
echo"After shuffling, the oruiginal string is: ".$string;
?>

Output:

Before shuffling, the string is: password
After shuffling, the new shuffled string is: rssawopd
After shuffling, the oruiginal string is: password

Caution:

The function can’t generate cryptographically secure values. If you want to create a cryptographically secure value, use random_int(), random_bytes()function rather than str_shuffle() function.

PHP Version Support:

PHP 4>= 4.3.0, PHP 5, PHP 7, PHP 8

Summary: PHP str_shuffle() Function

When it comes to shuffling characters, you can consider of the str_shuffle() function. It is one of the built-in PHP array function.

Reference:

https://www.php.net/manual/en/function.str-shuffle.php