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 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;
}
                        
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.