user1895377
user1895377

Reputation: 201

Condensing PHP code into functions

I have a repeating code in php that I would imagine I can somehow condense into a function and simply call the function multiple times. I tried doing this and nothing appears to happen. This is on repetition of the old code:

if ($health_1 > $health_2) {
    $health_left = '#7fba00';
    $health_right = '#e81123';
} else if ($health_perlvl_1 == $health_perlvl_2) {
    $health_left = '#0451ff';
    $health_right = '#0451ff';
} else {
    $health_left = '#e81123';
    $health_right = '#7fba00';
}

and this repeats about 12 times with other stats. I decided to try to condense it to this:

function stat_color($stat_1,$stat_2,$color_left,$color_right) {
    if ($stat_1 > $stat_2) {
        $color_left = '#7fba00';
        $color_right = '#e81123';
    } else if ($stat_1 == $stat_2) {
        $color_left = '#0451ff';
        $color_right = '#0451ff';
    } else {
        $color_left = '#e81123';
        $color_right = '#7fba00';
    }   

}
stat_color($health_1,$health_2,$health_left,$health_right);

But the colors are not there later when they are needed. Is there any way to actually get this to work?

Upvotes: 0

Views: 101

Answers (3)

Udit Narayan
Udit Narayan

Reputation: 109

Of course, since formal parameters are local to function scope their values cannot be used outside function. Try this.

Since we cannot return multiple values, I have used an array with appropriate keys.

function stat_color($stat_1,$stat_2) {

    $arr = array(); 
    if ($stat_1 > $stat_2) {
        $arr["color_left"] = '#7fba00';
        $arr["color_right"] = '#e81123';
    } else if ($stat_1 == $stat_2) {
        $arr["color_left"] = '#0451ff';
        $arr["color_right"] = '#0451ff';
    } else {
        $arr["color_left"] = '#e81123';
        $arr["color_right"] = '#7fba00';
    }   

    return arr;
}

You can now use:

$colors = stat_color(stat1,stat2);

Use $colors["color_left"] or $colors["color_right"] to refer to appropriate colors.

Upvotes: 1

halfer
halfer

Reputation: 20430

You could return the strings thus:

return array('#7fba00', '#e81123');

And then when you want to get them again:

list($health_left, $health_right) = stat_color($health_1, $health_2);

You can do this with pass-by-reference variables, but it feels less elegant.

Upvotes: 0

Rob
Rob

Reputation: 526

Try this:

function stat_color($stat_1,$stat_2,&$color_left,&$color_right) {

That way it will update the variables you pass into the function.

Upvotes: 2

Related Questions