Ternary operator doesn't evaluate the "false" value

Whats wrong with this:

foreach($projekte->children()->visible() as $projekt) { 
  $image = ($projekt->cover()->isNotEmpty() ? $projekt->image($projekt->cover()) : $projekt->images()->first());

If the there is no ->cover() it evaluates to nothing, if there is, everything is okay?!

Any help?

What do you mean with “it evaluates to nothing”? I can’t see anything wrong with this, but your code would fail if there is not image unless you test for the image?

So in any case, your code should look like this:

  <?php foreach($page->children()->visible() as $projekt) {
      $image = ($projekt->cover()->isNotEmpty() ? $projekt->image($projekt->cover()) : $projekt->images()->first());
      if($image) {
         // do something
      } 
    }
?>

Because even if the cover field is not empty, the image may not exist.

There are images, but if the “cover” field is empty it fails.

But still it is a good idea to ask for the $image :slight_smile:

Now it,s working,
I can’t see why, but thanks again for help!

There are two areas where the code may fail without the additional check:

  • one of the projects does not have any images in it
  • one of the projects does have a cover image in the content file, but the file does not exist anymore

I should have check for a variable before using it anyway!