0

How can I write a leap-year program in one line using PHP?

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
streetparade
  • 32,000
  • 37
  • 101
  • 123

6 Answers6

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
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
2

echo date("L");

Select0r
  • 12,234
  • 11
  • 45
  • 68
1

date("L"); is even shorter.

if(date("L")){
   //leap year
} else {
   //not leap year
}
OBL
  • 367
  • 1
  • 4
  • 13