在循环和if语句之外调用变量

Hello so I have some lines of code and what I'm trying to do is to echo out the variable in inside the loop. Here is the code:

if(!empty($output['txt_1'])) {
                $bind = array(
                    ":username" => $output['txt_1']
                );
                $accounts = $db->select("accounts", "username = :username", $bind);
                if(count($accounts) > 0) {
                    foreach ($accounts as $ac) {
                        $r_1 = $ac['sponsorID'];
                    }
                } else {
                    $sid = array(
                    ":sponsorID" => $randl1_1
                    );
                    $accounts = $db->select("accounts", "sponsorID = :sponsorID", $sid);

                    while(count($accounts) > 0) {
                        $r_1 = mt_rand(100000, 999999);
                    }
                }               
    }

echo $r_1;

Whenever I run the code, I get Undefined variable: r_1. I think it's because it's inside the loop, is there any chance to call out the variable outside the if statement and the loop? Thanks.

The value of $output['txt_1'] is considered empty and since that evaluates to true, your block inside the outer IF statement wont execute. therefore, the last echo $r_1 line gives the undefined error.

Define r_1 outside the if statement, first.