Am feeling dense… This is from a tutorial I am doing
you say evaluation, but it is not inside an if/else statement, so i guess that is what is confusing me. lol
The manual says a fetch returns an array or false.
public static function emailExists($email)
$sql = 'SELECT * FROM users WHERE email = :email';
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
return $stmt->fetch() !== false;
Because the function is called emailExists then it makes sense. It’s returning true if fetch gives a result and returning false if it doesn’t. If fetch returns null instead of false then this function would still return false keeping the type a boolean strictly speaking .
The last post hits the nail on the head. $stmt->fetch() returns an array, so when you return that from your emailExists function then that function would have a mixed return type, namely an array or false.
Generally functions with mixed return types are hard to work with, because every time you call them you have to inspect what they’ve returned to you and what that means. Whereas if you return $stmt->fetch() !== false then you always get a boolean return from that function, which is a lot easier to work with.
Based on the method name, emailExists, it is looking for a Boolean result and not the actual email for use, so let the DB tell you and then just return the fetch.
SELECT EXISTS (SELECT 1 FROM users WHERE email = :email)
My question though, especially that this code is from a tutorial, is WHY is the existence of an email being checked? This is generally done when doing a user registration which builds in a race condition. In that case the proper method would be to set a unique constraint on the email/username column. Attempt the insert, and then catch the duplicate error if any.
On your first example, the if and the else would be unnecessary. The first return basically acts as an exit or die. More importantly, $result is already going to be true (with a result) or false so there is no need for a redundant false check.
For some languages, when the value of an Int is zero, it’s an Int. For PHP a zero can be a zero, but when loosely compared a zero can evaluate to a Boolean false. eg. if you don’t want to risk code seeing a zero as a false, use strict comparison.
Similar concerns with nulls and empty strings. If it matters, be sure your conditionals test what you think they’re testing.