PHP str_shuffle Function | Shuffle Characters of a String

PHP str_shuffle is an inbuilt function in PHP. It randomly shuffles all the characters of the input string without altering the original string. Also, it also works on numbers by treating them as strings. It returns a string which is one of the permutations of characters of the input string. In this article, we will discuss the PHP str_shuffle Function. Also, we will discuss a few examples of using it.

Caution: This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.

Syntax

str_shuffle($string)

Parameters

The PHP str_shuffle Function expects only one parameter. The string which you want to shuffle is the input to the function. Also, an integer can also be passed as the parameter.

Return Value

The PHP str_shuffle returns a string after randomly shuffling the characters of the input string. Every time, the function returns a different sequence of characters. However, the function might also return the same input string occasionally.

PHP str_shuffle Function

Examples

Let’s discuss a few example of using the function.

Example 1: String Input

For instance, consider a simple string input to the function.

<?php

	$inputString = 'Concatly';
	$shuffled1 = str_shuffle($inputString);
	$shuffled2 = str_shuffle($inputString);

	print_r($shuffled1);
	print_r($shuffled2);

?>

In the above example, the function produces two different strings by randomly shuffling the input string.

OUTPUT:
oynCtacl
cnltyoaC

Example 2: Number Input

Similarly, you can also pass an integer/number to the function. It treats it as a string and shuffles it.

<?php

	$inputString = 12345;
	$shuffled1 = str_shuffle($inputString);
	$shuffled2 = str_shuffle($inputString);

	print_r($shuffled1);
	print_r($shuffled2);

?>
OUTPUT:
51243
43125

Conclusion

In this article, we discussed the PHP str_shuffle Function. You can read more about it on the Official PHP Documentation. Additionally, you can learn about more PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *