3

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';
}
fizzy drink
  • 682
  • 8
  • 21

2 Answers2

4

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.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
2

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105