What best practices should be followed when implementing a password generation function in PHP to ensure security and efficiency?

When implementing a password generation function in PHP, it is important to ensure that the generated passwords are strong and secure. This can be achieved by using a combination of uppercase and lowercase letters, numbers, and special characters. Additionally, the function should be efficient and not prone to common security vulnerabilities such as predictable patterns or easy-to-guess passwords.

function generatePassword($length = 12) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+';
    $password = '';
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    
    return $password;
}

$generatedPassword = generatePassword();
echo $generatedPassword;