How can I write a leap-year program in one line using PHP?
Asked
Active
Viewed 4,826 times
0
-
1Please define what you mean by a leap-year program? This could mean many things. – a'r Feb 26 '10 at 12:32
-
18Don't touch the enter key. – Quentin Feb 26 '10 at 12:32
-
With much use of the ternary operator... – Skilldrick Feb 26 '10 at 12:32
-
OK Define Leapyear: If Year % 400=0 Its Leap year If Year % 4 =0 Its also Leapyear and if Year % 100 its not a Leap year – streetparade Feb 26 '10 at 12:36
-
May I just ask (out of pure curiosity), why only one line? – Alxandr May 04 '10 at 00:50
6 Answers
15
This is how to know it using one line of code :)
print (date("L") == 1) ? "Leap Year" : "Not Leap Year";

Sarfraz
- 377,238
- 77
- 533
- 578
-
1
-
2
-
2@Gordon - date("L") returns bool already. `$isLeapYear = date("L");` is all you need. – thetaiko Feb 26 '10 at 13:21
-
3@thetaiko Not bool. String. `var_dump(date('L')); // string(1) "0"`. But since 1 and 0 would be typecasted as needed, yes, I agree it can be shortened even further. – Gordon Feb 26 '10 at 13:50
5
if (($year % 400 === 0) || (($year % 100 !== 0) && ($year % 4 === 0))) echo "leap";

Xr.
- 1,410
- 13
- 23
-
From http://stackoverflow.com/questions/3220163/how-to-find-leap-year/#11595914 `if (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0) { /* leap year */ }` – Kevin P. Rice Jul 21 '12 at 23:55
-
I would not want to maintain that code. Bit operations for something that is only arithmetic are cryptic. The original answer you quote considered performance, so it might be relevant in some cases. But for all other cases, I'd rather keep a readable expression. – Xr. Jul 23 '12 at 10:13
-
I usually place a URL in a comment when something is cryptic; or, place the code in a function like "IsLeapYear" where it is clear what it does. Since the Gregorian Calendar isn't changing any time soon, I don't think "maintainability" is much of a concern. This code can be more than twice as fast, and even ten times faster in 8-bit embedded system CPUs where there is no divide instruction. – Kevin P. Rice Jul 23 '12 at 17:36
3
Since there is no limit in how long a line of code is, unless you are using a code convention like that of Zend Framework, you can use whatever works and write into one line. Of course, depending on the functionality of your leap-year program, this will likely be hard to maintain. I've seen legacy code running over 800 chars with PHP, HTML and CSS intermingled. Eye-bleeding, I can tell you.

Gordon
- 312,688
- 75
- 539
- 559
2
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);

Bastiaan Linders
- 1,861
- 2
- 13
- 15
-
Ah! I didn't know the meaning of leap-year, sorry. But I'll keep this "answer" here in case people end up here with the question that I thought you asked! – Bastiaan Linders Feb 26 '10 at 12:39