Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing 3 nested if-then-else

Tags:

php

I'm seeing this code as the equivalent of a mathematical permutation. It tries to set the value of $d based on a combination of $a, $b, $c. Right now it's being done with 3 nested if/then/else. Any other way the same thing can be done more efficiently?

if ($a === true) {
    if ($b > 0) {
        if ($c === true) {
            $d = 6;
        } else {
            $d = 2;
        }
        $e = $b;
    } else {
        if ($c === true) {
            $d = 4;
        } else {
            $d = 0;
        }
    }
} else {
    if ($b > 0) {
        if ($c === true) {
            $d = 5;
        } else {
            $d = 1;
        }
        $e = $b;
    } else {
        if ($c === true) {
            $d = 7;
        } else {
            $d = 3;
        }
    }
}

Notice there's $e = $b; at the end of

if ($a === true) {
    if ($b > 0) {
} else {
    if ($b > 0) {

I think I will just remove it out of the whole look and say

if ($b > 0) {

Any error with that logic for $e = $b;?

like image 834
switch Avatar asked Apr 19 '26 04:04

switch


1 Answers

You could do this:

$vals = array(3,7,1,5,0,4,2,6);
$d = $vals[((int)($a === true) << 2) + ((int)($b > 0) << 1) + (int)($c === true)];
if ($b > 0) {
    $e = $b;
}

This takes each condition as a bit in a 3 bit value to determine the index of the value for d:

index = a·2^2 + b·2^1 + c·2^0

Each condition yields a boolean value that is converted to integer (see boolean to integer conversion) and then shifted according to the position of the bit it represents (see shift left operator <<).

like image 82
Gumbo Avatar answered Apr 21 '26 17:04

Gumbo