递归函数不会返回

时间:2016-09-05 10:44:54

标签: php recursion

<?php

function generateRandomString($length = 10, $alpha = false, $numeric = false) {

  if ($alpha)   { $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; }
  if ($numeric) { $characters = '0123456789'; }

  $charactersLength = strlen($characters);
  $randomString = '';

  for ($i = 0; $i < $length; ++$i) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
  }

  if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
    generateRandomString($length, $alpha, $numeric); // try again
  }
  else {
    return $randomString;
  }
}

$num = generateRandomString(8, false, true);
echo ($num);

我需要它返回一个以2开头的值,但它根本不返回任何内容,也没有错误。我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

使用return here,更改此

if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
  generateRandomString($length, $alpha, $numeric); // try again
}

if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
 return generateRandomString($length, $alpha, $numeric); // try again
}