M0UNTAIN 0F C0DE

First XOR

PHP logic

I've been writing PHP for over 15 years at this point, and not once have I ever had a need to use the logical xor operator, until now!

It came up while writing a feature which matched email addresses from an email_logs table to the users table, in this app there were two types of users, admins and customers; they're stored in different tables.

The naive approach would be to try one and then the other:

$user = CustomerUser::query()
    ->where('email', $log->getToAddress())
    ->first();

$user ??= AdminUser::query()
    ->where('email', $log->getToAddress())
    ->first();

There's a problem with this approach. What if an email address appears in both the AdminUser table and the CustomerUser table? This wasn't just theoretical, this was something we actually needed to consider. Enter the xor:

$customerUser = CustomerUser::query()
    ->where('email', $log->getToAddress())
    ->first();

$adminUser = AdminUser::query()
    ->where('email', $log->getToAddress())
    ->first();

if ($customerUser === null xor $adminUser === null) {
    $user = $customerUser ?? $adminUser;
}