PHP str_shuffle() Function

Usage — The PHP str_shuffle() function is used to randomly shuffle a given string.

It has the following syntax:


string str_shuffle ( string $str )

Here is an example of using str_shuffle():


// Output — _oor_Hgnowyu_?aied
echo str_shuffle("How_are_you_doing?");

Return Value — This function returns the shuffled string which is just one random permutation out of all the possibilities.

Additional Information — This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int , random_bytes , or openssl_random_pseudo_bytes instead.

PHP Version and Changelog — The str_shuffle() function is available in PHP 4 >= 4.3.0, PHP 5, PHP 7. In PHP version 7.1.0, the internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.

Relevant Functions — Other related PHP functions that you should know about are: shuffle which shuffles an array and rand which generates a random integer.

Go Directly To — usage, parameters, working examples or additional tips.



The str parameter is used to specify the input string that you want to shuffle. This is a required parameter.

Working Examples

Here are some examples of using the str_shuffle() function:


$str = '123456';
$shuffled = str_shuffle($str);
// Output — 426351
echo $shuffled;

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

    Hree’s a cdoe taht slerbmcas txet in tihs way:


    function scramble_word($word) {
        if (strlen($word) < 2)
            return $word;
        return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    // Output — A qciuk borwn fox jmpued oevr the lazy dog.
    echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');

    It may be useful if you wnat to cetare an aessblicce CTCPAHA.

    Suggested by - jojersztajner at OXYGEN dot POLAND

Further Reading

  1. You can read more about the PHP str_shuffle() function on

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

Go To Top