简体   繁体   中英

Php elseif condition in foreach

I have this problem regarding an if/elseif condition in a foreach look. I have searched over and over and really out of ideas. So I have this array:

Array (

[0] => stdClass Object
    (
        [title] => main
        [value] => value1
    )

[1] => stdClass Object
    (
        [title] => other
        [value] => value2
    )

[2] => stdClass Object
    (
        [title] => second
        [value] => value3
    )

[3] => stdClass Object
    (
        [title] => other
        [value] => value4
    )

[4] => stdClass Object
    (
        [title] => other
        [value] => value5
    )

)

As you can see obj0 has title=>main and obj2 has title=>second, the rest of "titles" are set to other.

I have this foreach:

foreach ($objects as $object): 
    if($object->title == 'second') { 
        //this value is rarely added, so it must have a "priority" and be showed
        echo '<span></span>';
    } elseif($object->title == 'main') { 
        //i mostly want to show this, but not if $object->title has the value 'second'.
        echo '<div></div>';
    }
endforeach;

This loop returnes both "span" and "div" which i don't want. I can't manage to show only title=>"second" (if it's there), and title=>"main" only if "second" doesn't exist. So either display spans, either div's.

Hope i explained good, if not i apologize! Thank you very much and i really appreciate your help!

Marius

If either may appear at any position in the array - ie main may appear before second (as appears to be the case) - you will have to loop the entire array before making the decision what to display:

$main = $second = FALSE;
foreach ($objects as $object): 
    if($object->title == 'second') { 
        $second = TRUE;
        break; // Added as @PeterKrejci pointed out
    } elseif($object->title == 'main') { 
        $main = TRUE;
    }
endforeach;

if($second) { 
    echo '<span></span>';
} elseif($main) { 
    echo '<div></div>';
}

If second will always appear before main , all that is needed is a couple of break s:

foreach ($objects as $object): 
    if($object->title == 'second') { 
        echo '<span></span>';
        break;
    } elseif($object->title == 'main') { 
        echo '<div></div>';
        break;
    }
endforeach;

Foreach iterates over all entries in that array, so you have to break it after first match, you can use break; after that echo to jump out of foreach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM