简体   繁体   中英

ternary foreach nested within if / else

I was wondering how I can rewrite the following using ternary within ternary or within alternative syntax.

$tags = get_the_tags();
if (!empty($tags)) {
    foreach ($tags as $tag) {
        echo $tag->name . ', ';
    }    
} else {
    echo 'foobar';
}

No such thing as ternary foreach. You can however make your conditional statement ternary like this

echo empty($tags) ? 'foobar' :
implode(', ',array_map(create_function('$o', 'return $o->name;'),$tags)) ;

;)

Output

foo, bar, John

Explanation

We create a closure that returns an array of the name property of all your tags then simply implode it like you want. If tags are empty we show foobar , all in one line.

Solution with array_reduce :

echo (empty($tags))? 'foobar': array_reduce($tags, function($prev, $item){
    return $prev.(($prev)? ", " : "").$item->name;
}, "");

// the output:
bob, john, max

http://php.net/manual/ru/function.array-reduce.php

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