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

PHP / Class, Object and Methods

115

Given Input:


Expected Output:


Program:

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;
}

Output:


                                                                     
                              

This Particular section is dedicated to Programs only. If you want learn more about PHP. Then you can visit below links to get more depth on this subject.