Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if function parameter is set

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?

like image 364
Josif Avatar asked Apr 22 '11 13:04

Josif


2 Answers

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

like image 135
kapa Avatar answered Sep 30 '22 06:09

kapa


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.

  1. don't echo from within functions, return the result and echo it from your view or view related code parts
  2. write readable variable and function names
  3. don't overwrite input variables, build new ones

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;
like image 20
markus Avatar answered Sep 30 '22 06:09

markus