简体   繁体   中英

PHP Syntax and Reasoning with Date If/Else Statement

I am working on a project and I have encountered this code:

$year    = date('Y') - (date('n') > 9 ? 0 : 1);

The way I read it, it seems to be; if the year (2014) minus the month (12) is greater than 9, then the Boolean is False, Otherwise it is true.

However when I go to print the variable, it prints 2014. I then changed 9 to 9000 to see what would happen, and it changed to 2013. I know this sound rudimentary but I can't understand why and I wasn't able to immediately find on google how this makes sense.

EDIT: Sorry, there was a leftover parentheses at the end of the code that wasn't supposed to be there. The code has been edited.

If you change the function calls of date() your code would look like this:

$year    = 2014 - (12 > 9 ? 0 : 1);

Now you may see better that 12 is greater then 9 and it is TRUE! So 0 get's 'used':

$year    = 2014 - 0;

So the result is:

2014

Your adoption is wrong that the ternary operator condition is false!

This looks like a formula for getting the fiscal year. The parenthetical evaluates to 0 if the month is Oct-Dec, 1 otherwise. So it subtracts 1 from the current year unless the date is after Sep 30.

I don't think you noticed the extra paranthesis around the second date parameter.

You're reading the code like this:

date('Y') - date('n')

But, the code actually says:

data('Y') - 1 // or 0 (depending on the returned int from the ternary operation)

Another way to write it is:

$dateX = date('Y');
$dateY = (date('n') > 9 ? 0 : 1);
$result = $dateX-$dateY;
// result will output either 2014 (from $dateX) or 2013 (if $dateY equals 1)

Try it like this.

 $year    = (date('Y') - (date('n')) > 9 ? "false" : "true");
 echo $year; //this will give you false.

Or like this,

 $year    = (date('Y') - (date('n')) > 9 ? 0 : 1);
 echo $year; //this will give you 0.

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