Skip to content
Related Articles
Open in App
Not now

Related Articles

PHP | str_shuffle() Function

Improve Article
Save Article
  • Last Updated : 20 Aug, 2020
Improve Article
Save Article


The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter.

Syntax:

str_shuffle($string) 

Parameter: This function accepts a single parameter $string. The parameter $string specifies the string whose characters are needed to be shuffled. In place of a string, a number can also be passed. If a number is passed instead of a string as a parameter then this function will treat that number as a string.

Return Value: The function returns a string of the same length but with shuffled characters within itself. Every time the program is executed, it displays a different output since shuffling of characters is different every time. The original string or the number can be the return value on some occasions.

Examples:

Input : $string = "raj" 
Output : jar 

Input : $string = "geeks" 
Output : eeksg 

Input : $string = 142 
Output : 412 

Note: The output will be different on every execution. 

Below programs illustrate the str_shuffle() function:

Program 1: Program to demonstrate the str_shuffle() function when a string is passed.




<?php
// PHP program to demonstrate the str_shuffle()
// function when a string is passed
$string = "geeks"
  
// prints the shuffled string 
echo str_shuffle($string);
?>

Output:

keegs

Program 2: Program to demonstrate the str_shuffle() function when a number is passed.




<?php
// PHP program to demonstrate the str_shuffle()
// function when a number is passed
$string = 142; 
  
// prints the shuffled string 
echo str_shuffle($string);
?>

Output:

124

Reference:
http://php.net/manual/en/function.str-shuffle.php

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!