Why is this function going into infinite loop?

Asked

Viewed 61 times

-3

I made this function to return a unique code ( it checks if already exists searching in a webservice), but when run, it is running forever, does not return me result.

public function generateuniquecode(){
    function generatecode(){
      $upper = implode('', range('A', 'Z')); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
      $nums = implode('', range(0, 9)); // 0123456789
      $alphaNumeric = $upper.$nums; // ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
      $code = '';
      for($i = 0; $i < 6; $i++) {
          $code .= $alphaNumeric[rand(0, strlen($alphaNumeric) - 1)];
      }
      return $code; // ex: X0XX0X
    }
    $exists = false;
    while($exists == false) {
      $code = generatecode();
      $response = $this->seachcardbycode($code);
      if($response['success'] == false){
        if($response['data']['code'] == 1){
          $exists = false;
        }else{
          die('code 0');
          // code 0
          // curl call error
        }
      }else{
        $exists = true;
      }
    }
    return $code; 
  }

The seachcardbycode function returns an array like this:

array(
      "success"=>false / true,
      "data"=>outro array
    );
  • Have you tried to make the impression of the objects that the $response refers?

1 answer

0

Apparently the problem is in your code, in the section where starts the IF.

if($response['success'] == false)

To be more precise in the answer would be interesting you post the code of the whole function the seachcardbycode. To see the possibilities of the value of $response['success'] be amended. At first it always comes with the value false thus the Else will never be triggered, and the value of $existes will never be changed.

If it is not passed to $response no object where Success is equal to false, really will stay in an infinite loop this code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.