1

I have a simple code here:

$rand     = mt_rand(100000, 999999);
$sid      = array(
    ":sponsorID" => $rand
);
$accounts = $db->select("accounts", "sponsorID = :sponsorID", $sid);
while (count($accounts) > 0) {

    $new = mt_rand(100000, 999999);
}
echo $new;

What it basically does is to check if the generated number from $rand is already in the database and will set a $new variable. My problem is when I echo out $new, I always get an undefined index of that variable. How can I call that variable outside the while loop?

9
  • What is the sense of this? Why would you overwrite that variable $new in all iterations? I assume you want to add a break or continue statement to that loop... Also: this will be an endless loop once there is an entry in the database, since you do not modify $accounts inside the loop... Commented Aug 2, 2015 at 6:46
  • @arkascha thank you for pointing that out.. I forgot that. Should I use continue because I want it to go back to the condition when it is already present in the database Commented Aug 2, 2015 at 6:49
  • @arkascha Will I still get an endless loop with my code? Commented Aug 2, 2015 at 6:54
  • @arkascha Then I should use do while loop right? Commented Aug 2, 2015 at 6:56
  • I could imagine your want to use a for or a foreach loop instead of that while... Commented Aug 2, 2015 at 6:57

2 Answers 2

3

You are only defining $new inside the loop, so it's undefined outside it. Just declare it before the loop and you should be fine:

$new = NULL;
while (count($accounts) > 0) {
    $new = mt_rand(100000, 999999);
}
echo $new;
Sign up to request clarification or add additional context in comments.

1 Comment

I always get null with this
1

There are a few issues with your code. This is a modified version that outputs what you are looking for:

<?php 

$sid = array(
  ":sponsorID" => $rand
);
$accounts = $db->select("accounts", "sponsorID = :sponsorID", $sid);

$new = null; 
do { 
  $new = mt_rand(100000, 999999); 
} while (in_array($new, array_column($accounts, 'sponsorId'))); 

echo $new; 

Note: this requires at least php 5.5 because of the array_column() call. But that makes the code simple and easy to understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.