Home > Mobile >  Simplify multiple nested if()'s
Simplify multiple nested if()'s

Time:05-24

Can someone help me simplify this complex nested if()'s algorithm? I know it can be simplified, but I'm afraid I'll mess up with the multiple conditions if I trust myself.

$groups = array();

foreach ($items as $item) {
    if ($item['group_code']) {
        if (array_key_exists($item['group_code'], $groups)) {
            if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])) {
                $groups[$item['group_code']] = $item['title'];
            }
        } else {
            $groups[$item['group_code']] = $item['title'];
        }
    } else {
        $groups[$item['item_code']] = $item['title'];
    }
}

What I want is to create an index of product titles in $groups. If group_code key exists for each item, then I want to store the lengthier title of all items belonging to that group. If group_code doesn't exist (meaning it's a single product and not a grouped one), I want to store the title of that item using the item_code instead (this is the simplest condition, and no length comparison is needed here).

CodePudding user response:

What about checking the else conditions first?

foreach ($items as $item) {
    if (!isset($item['group_code'])){
        $groups[$item['item_code']] = $item['title'];
    } else if (!array_key_exists($item['group_code'], $groups)){
        $groups[$item['group_code']] = $item['title'];
    } else if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])){
        $groups[$item['group_code']] = $item['title'];
    }
}

CodePudding user response:

I'd simplify it like this (php 7 ):

foreach ($items as $item) {
    $t = $item['title'];
    $c = $item['group_code'] ?? $item['item_code'];
    if (mb_strlen($t) > mb_strlen($groups[$c] ?? '')) $groups[$c] = $t;
}

CodePudding user response:

Maybe it's a bit late as well as a bit complex code at first glance (but it actually easy to understand), here is my answer:

foreach ($items as $item) {
    if (!isset($item['group_code'])){
        $groups[$item['item_code']] = $item['title'];
    } else{
        $groups[$item['group_code']] = (!array_key_exists($item['group_code'], $groups) ? $item['title'] : (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title']) ? $item['title'] : ''));
    }
}
  • Related