0

how can I do this little function in PHP, my specific doubt is in the part that I use the IF conditionals in the code that I share, this can't be run, I don't know if I can do something like that in PHP, how can I do this correctly. I really will appreciate your help!

function updateAvg_noi($bean, $event, $arguments)
         {
            $bean->avg_noi_c = ($bean->year_1_noi_c + $bean->year_2_noi_c + $bean->year_3_noi_c) / 
            (
                (if($bean->year_1_c == NULL){0;}else{1;}) + 
                (if($bean->year_2_c == NULL){0;}else{1;}) + 
                (if($bean->year_3_c == NULL){0;}else{1;})
            );
         }
  • Use the conditional operator, aka ternary: `condition ? true-value : false-value` – Barmar Aug 21 '20 at 00:45
  • 1
    Does this answer your question? [How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?](https://stackoverflow.com/questions/1506527/how-do-i-use-the-ternary-operator-in-php-as-a-shorthand-for-if-else) – Cornel Raiu Aug 21 '20 at 00:46
  • Thank you very much, it is what I was looking for. :) – Carolina VG Aug 21 '20 at 22:27

2 Answers2

1

The ternary operator is what you are looking for in this case

function updateAvg_noi($bean, $event, $arguments) {
    $bean->avg_noi_c = ($bean->year_1_noi_c + $bean->year_2_noi_c + $bean->year_3_noi_c) / (
        (($bean->year_1_c == NULL) ? 0 : 1) + 
        (($bean->year_2_c == NULL) ? 0 : 1) + 
        (($bean->year_3_c == NULL) ? 0 : 1)
    );
}
Cornel Raiu
  • 2,758
  • 3
  • 22
  • 31
0

This is just an alternative way of doing the calculation if you have lots of year inputs. Ex. year 4, year 5, ...

<?php

// Alternatives using array_sum

// Ex. Ternary operator
$numerators = [
    $bean->year_1_noi_c, 
    $bean->year_2_noi_c, 
    $bean->year_3_noi_c
];

$denominators = [
    $bean->year_1_c === null ? 0 : 1,
    $bean->year_2_c === null ? 0 : 1,
    $bean->year_3_c === null ? 0 : 1,
];

$output = array_sum($numerators) / array_sum($denominators);


/***********************************************************/


// Ex. Check is_null, inverse, cast to int
$numerators = [
    $bean->year_1_noi_c, 
    $bean->year_2_noi_c, 
    $bean->year_3_noi_c
];

$denominators = [
    (int)!is_null($bean->year_1_c),
    (int)!is_null($bean->year_2_c),
    (int)!is_null($bean->year_3_c)
];

$output = array_sum($numerators) / array_sum($denominators);
waterloomatt
  • 3,662
  • 1
  • 19
  • 25