Are there any common pitfalls to avoid when creating a nested referral system in PHP?

One common pitfall to avoid when creating a nested referral system in PHP is the potential for infinite loops or circular references. To prevent this, you can implement a check to ensure that a user cannot refer themselves or refer someone who has already referred them. This can be done by keeping track of the referral hierarchy and checking for any loops before adding a new referral.

function addReferral($referrer, $referee, $referralHierarchy) {
    if ($referrer == $referee || checkForLoop($referrer, $referee, $referralHierarchy)) {
        return false;
    }
    
    // Add referral logic here
    
    return true;
}

function checkForLoop($referrer, $referee, $referralHierarchy) {
    $currentReferrer = $referrer;
    
    while (isset($referralHierarchy[$currentReferrer])) {
        if ($referralHierarchy[$currentReferrer] == $referee) {
            return true;
        }
        
        $currentReferrer = $referralHierarchy[$currentReferrer];
    }
    
    return false;
}