Search code examples
phpconditional-statementsnested-if

Simplify multiple nested if()'s


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 the 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).


Solution

  • 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'];
        }
    }