I got a function:
- which should add to number $x random number from -25 to 25
- if result is higher than 255 or lower than 0, the function should be called again to generate acceptable result.
What I got is:
function changeParam($base_val)
{
$plus = mt_rand(-25, 25);
if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
{
changeParam($base_val); //is it correct?
}
else
{
$new_val = $base_val + $plus;
return $new_val;
}
}
Why this:
$x = changeParam(255);
var_dump($x);
does give me null sometimes?
I've tried to check it, but I didn't find the reason:
function changeParam($base_val)
{
$plus = mt_rand(-25, 25);
if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
{
changeParam($base_val);
}
else
{
$new_val = $base_val + $plus;
echo 'Is there a problem? ' . $new_val; // this line shows correct new_val
var_dump($new_val); // correct, for instance: 'int 250'
return $new_val; // but in the same time, the result = 'null'
}
}
If you really want to go with recursion, you have to add a return
before the call to changeParam($base_val);
. So it would look like this:
function changeParam($base_val)
{
$plus = mt_rand(-25, 25);
if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
{
return changeParam($base_val); // CHANGED HERE
}
else
{
$new_val = $base_val + $plus;
return $new_val;
}
}
However, recursion in such a case can potentially be bad. (If the search for the random variable happens to return "bad" values too many times, you might run into a stack overflow exception. The probability of this happening in this specific case is pretty low - but you should always consider such a case.)
Instead, you should go with an iterative approach, for example like this:
function changeParam($base_val)
{
$plus = mt_rand(-25, 25);
while (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
{
$plus = mt_rand(-25, 25);
}
$new_val = $base_val + $plus;
return $new_val;
}
function changeParam($base_val)
{
$plus = mt_rand(-25, 25);
if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
{
$new_val = changeParam($base_val);
}
else
{
$new_val = $base_val + $plus;
}
// return here
return $new_val;
}