Compare year values of dates and change their formatting if it is the same value

I want to check if the startdate()->toDate(‘y’) and enddate()->toDate(‘y’) have the same value. If so it should then change the date format to startdate()->toDate(‘j M’) (to be without a year).

I have skimmed the forum and have so far stumbled upon using a basic if else statement to compare the two values but it keeps throwing me a “Can’t use method return value in write context” Error. What am I doing wrong?

Here are both my non functional tries:

1. using e()
<?= e($exhibition->startdate()->toDate('y') = $exhibition->enddate()->toDate('y'), $exhibition->startdate()->toDate('j M y'), $exhibition->startdate()->toDate('j M')) ?>

2. using if else
if($exhibition->startdate()->toDate('y') = $exhibition->enddate()->toDate('y')) {
   echo "$exhibition->startdate()->toDate('j M')";
   } else {
   echo "$exhibition->startdate()->toDate('j M y')";
}

Please try with comparison operators like equal (==) or identical (===) operator instead assignment (=) operator:

if($exhibition->startdate()->toDate('y') === $exhibition->enddate()->toDate('y')) {
  //
}
2 Likes

Just on a side note: the e() helper already echos something, so you don’t need the short echo tag (<?=) in addition:

Either:

<?php e($exhibition->startdate()->toDate('y') === $exhibition->enddate()->toDate('y'), $exhibition->startdate()->toDate('j M y'), $exhibition->startdate()->toDate('j M')) ?>

Or using the ternary operator with the short echo tag:

<?= $exhibition->startdate()->toDate('y') === $exhibition->enddate()->toDate('y') ? $exhibition->startdate()->toDate('j M y') : $exhibition->startdate()->toDate('j M') ?>
2 Likes