Home / Programs / Write a PHP function to generate a random password. The password should contain uppercase, lowercase, numeric and other
Programming Example

Write a PHP function to generate a random password. The password should contain uppercase, lowercase, numeric and other

👁 175 Views
💻 Practical Program
📘 Step by Step Learning

1. PHP Random password generation Write a PHP function to generate a random password. The password should contain uppercase, lowercase, numeric and other Create password using shuffle() function.

Information & Algorithm

Given Input:


Expected Output:


Program Code

function generate_password($length = 12) {
    // Define all possible characters that can be used in the password
    $uppercase = range('A', 'Z');
    $lowercase = range('a', 'z');
    $numbers = range('0', '9');
    $special_chars = str_split('!@#$%^&*()_+={}[];\',.');

    // Combine all characters into a single array
    $all_chars = array_merge($uppercase, $lowercase, $numbers, $special_chars);

    // Shuffle the array
    shuffle($all_chars);

    // Take a random subset of the shuffled array to create the password
    $password = array_slice($all_chars, 0, $length);

    // Convert the array to a string
    $password = implode('', $password);

    // Return the password
    return $password;
}

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.