I have a function that loads a butterfly image.
There are 3 possible parameters: colour, angle and position
The last one is always explicitly set, but the first 2, if not set, are determined with a random number. This means that the function will always load a nice randomly coloured and angled butterfly, unless specifically set.
I have this
function randombf ($randbf,$randangle,$position) {
$randbf = rand(1,4);
$randangle = rand(1,4);
echo '<div class="bf '.$position.'" style="background:url(\'images/bf_'.$randangle.'_'.$randbf.'.png\');"></div>';
}
Now the problem I have is that I would only like the random to be set if the parameters aren't passed.
Something like:
if(!$randbf) {
$randbf = rand(1,4);
}
But that doesn't work if I pass
randombf('1','2','whatever')
It performs the random regardless.
What am I doing wrong?
You should change the order of your parameters. Put position first because it will be always specified. If you do it this way, you will be able to write randombf(12)
or randombf(12, 1, 2)
or even randombf(12, 1)
.
Omitted parameters will be set to null
(you can specify anything else if you want, but only scalar values), so you only have to check if the var is_null()
.
function randombf ($position, $randbf = null, $randangle = null) {
if (is_null($randbf)) $randbf = rand(1,4);
if (is_null($randangle)) $randangle = rand(1,4);
echo '<div class="bf '.$position.'" style="background:url(\'images/bf_'.$randangle.'_'.$randbf.'.png\');"></div>';
}
Let me incorporate the link @Matt Ball has posted into my answer:
Default function arguments
What @bazmegakapa says about the order of your input parameters and making the second and the third parameter optional is correct. But he doesn't point out a few other important things about your code.
Your function could look something like that:
function getRandomButterfly ($position, $butterfly = null, $angle = null)
{
if (is_null($butterfly)
{
$randomButterfly = rand(1, 4);
}
else
{
$randomButterfly = $butterfly;
}
if (is_null($angle)
{
$randomAngle = rand(1, 4);
}
else
{
$randomAngle = $angle;
}
$markup =
'<div class="bf '.$position.'" style="background:url(\'images/bf_'.$randomAngle.'_'.$randomButterfly.'.png\');"></div>';
return $markup;
}
$markup = getRandomButterfly(3);
echo $markup;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With