The following method is designed to return true
if it passes all of the rules for a password. Does anyone see a way to improve it? Performance improvements are welcome for sake of education.
I already know password rules beside length are counter-productive. It's not my choice. Also, I know that performance is absolutely trivial here. I only care about performance by way of educating myself. The stuff I learn on non-critical optimization often helps me when I do have a bottleneck. I will not be implementing something just because it is faster.
/**
* Returns true if and only if a password passes the rules:
* - Must be at least 8 characters.
* - Must contain two of the following types:
* - Letters
* - Numbers
* - Symbols (includes whitespace)
*
* @param string $password The raw, unencrypted password.
* @return bool
*/
public function isValidPassword($password) {
$length = strlen($password);
if ($length < 8) {
return false;
}
$foundLetter = false;
$foundNumber = false;
$foundSymbol = false;
for ($i = 0; $i < $length; $i++) {
$char = $length[$i];
if (ctype_alpha($char)) {
$foundLetter = true;
}
else if (ctype_digit($char)) {
$foundNumber = true;
}
else if (ctype_punct($char) || ctype_space($char)) {
$foundSymbol = true;
}
}
return ($foundLetter && $foundNumber)
|| ($foundLetter && $foundSymbol)
|| ($foundNumber && $foundSymbol);
}