Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

recursion - How to use return inside a recursive functions in php

Here is my question I am trying to create a random bar code for my application, I want to check if that code is already in the column than generate a new number, check it again if its unique return it to the caller else generate again. I am using a recursive function for this purpose. I have added number 1,2,3,4 inside my database so every time it runs it has to show me 5,6,7,8,9 or 10.

Here is my function:

function generate_barcode(){
    $barcode = rand(1,10);
    $bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
    if($bquery==1){
        generate_barcode();
    }else{
        return $barcode;    
    }
 }

And I just tested it like this

 $a = generate_barcode();
 if(isset($a))
 {
   echo $a;
 }
 else
 {
  echo 'Not Set';
 }  

So the problem is that its sometime showing me "Not Set", but I want it to always generate a unique number. I am not inserting the data so its not a problem that all the numbers are reserved.

Someone just guide me and let me know what is wrong with the code. I can use other approaches to do that but I need to know what is wrong with the supplied code. Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to return the generated number from your recursive call too, like

function generate_barcode()
{
    $barcode = rand(1,10);
   $bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
    if($bquery==1)
    {
    return generate_barcode(); // changed!
    }
    else
    {
    return $barcode;    
    }
 }

(You should include some kind of exit for the case that all numbers are 'taken'. This current version will call itself recursively until the PHP recursion limit is reached and will then throw an error.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...