w3resource

PHP Array Exercises : Generate a random password using shuffle() function


27. Generate Random Password Using Shuffle

Write a PHP function to generate a random password (contains uppercase, lowercase, numeric and other) using shuffle() function.

Sample Solution:

PHP Code:


<?php
// Define a function to generate a random password with specified character categories
function rand_Pass($upper = 1, $lower = 5, $numeric = 3, $other = 2) { 
    
    // Initialize an empty array to store the characters of the password
    $pass_order = Array(); 
    
    // Initialize an empty string to store the final password
    $passWord = ''; 

    // Create contents of the password with uppercase letters
    for ($i = 0; $i < $upper; $i++) { 
        $pass_order[] = chr(rand(65, 90)); 
    } 
    
    // Create contents of the password with lowercase letters
    for ($i = 0; $i < $lower; $i++) { 
        $pass_order[] = chr(rand(97, 122)); 
    } 
    
    // Create contents of the password with numeric digits
    for ($i = 0; $i < $numeric; $i++) { 
        $pass_order[] = chr(rand(48, 57)); 
    } 
    
    // Create contents of the password with other special characters
    for ($i = 0; $i < $other; $i++) { 
        $pass_order[] = chr(rand(33, 47)); 
    } 

    // Shuffle the order of characters using shuffle()
    shuffle($pass_order); 

    // Concatenate the characters to form the final password string
    foreach ($pass_order as $char) { 
        $passWord .= $char; 
    } 
    
    // Return the generated password
    return $passWord; 
} 

// Display the generated password
echo "\n" . "Generated Password : " . rand_Pass() . "\n";
?>

Output:

Generated Password : h1'1#h7Gqfy

Flowchart:

Flowchart: PHP - Generate a random password using shuffle() function

For more Practice: Solve these Related Problems:

  • Write a PHP function to generate a random password with a specified length, including uppercase, lowercase, numbers, and symbols, using shuffle().
  • Write a PHP script to generate multiple random passwords and display them in a formatted list, ensuring uniqueness.
  • Write a PHP program to combine different character sets, shuffle them, and then extract a random subset as a password.
  • Write a PHP script to implement a function that generates a secure random password and tests its complexity using regular expressions.

Go to:


PREV : Shuffle Associative Array Preserving Keys.
NEXT : Reverse Sort Array.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.