How to use return inside a recursive function in PHP

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.)

Leave a Comment