Mitchell B Mitchell B - 5 months ago 11
PHP Question

Would someone give an explanation of this PHP switch block?

I'd like to ask what this code is doing, and if someone could explain to me with comments?

I am trying to understand what it is doing. I am guessing it switches between them depending on the result of the statements E.g. 2 < 1 and 2 > 1. Then it is setting the dates in a year month day format?

Am I on the right track?

switch (true) {
case ($UserBirthday < $CurrentDate2) :
$CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
break;

case ($CurrentDate2 < $UserBirthday) :
$UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
break;
}

$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1;


Also, can I change it to an if/else statement like this?

if ($UserBirthday < $CurrentDate2) {
$CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
}

else if ($CurrentDate2 < $UserBirthday) {
$UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
}


$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1;

Answer

While there doesn't appear to be any benefit from using switch over if..elseif..else statements in your code example, switch is often used in place of long, ugly if..elseif..elseif..elseif..etc. statements. I suspect this is what the author of your code example was modeling.

You can read about switch's many uses at http://phpswitch.com/.