Multiply by the boolean result of a number

1

I have the hours worked by a worker and the daily salary. Such that:

$horas = 8;
$precio = 88;

$pagar = 0;
if($horas > 0){
    $pagar = $precio
}

return $pagar.

Work what you work, unless $horas is 0, I'll pay for the day. Then I would like to save the if (in the real code it is all more complex although in the example it seems simple). I have this:

$pagar = $precio * ($horas/$horas); 

Of course this is that if $horas is 8 and divided among itself is 1, and I can multiply it well. The fact is that if $horas is 0, splitting between is not quite correct.

And here the question of the title, can I multiply directly by the Boolean result of the number? that is, something like:

$precio * intval(boolval($horas)); 

this case works, but not in PHP 5.4 , since boolval is for PHP 5.5+ and I also think it should be simpler than calling 2 functions

Thanks

    
asked by Txmx 07.08.2018 в 12:13
source

2 answers

1

You could consider using a ternary operator (or Elvis) to assign the value directly from the number of hours. It would be something quite simple:

$pagar = $horas ? $precio : 0;

The idea is that numbers evaluate to true provided they are not zero. (Assuming you're not going to have a negative number of hours, which would not make much sense). So if $horas is not zero, $pagar receives the value $precio , otherwise it receives the value 0.

    
answered by 07.08.2018 / 12:30
source
2

How about something like that?

function pagar ($horas) {
    $precio = 88;
    return ($horas ? $precio : 0);
}

Here is a demo .

    
answered by 07.08.2018 в 12:30