Calculate Age: One-Liner Fun

PHP 1 Comment

Here's a little one-liner I thought up today for this PHPBuilder forum thread. It's purpose is to calculate someone's age when you know the year, month, and day of their birth (integer values). In this snippet it is assumed that $year, $month, and $day hold the integer values for the birthday of interest.

$today = time();
for($yr = $year, $age = -1; mktime(0,0,0,$month,$day,$yr) < $today; $yr++, $age++);
echo $age;

This utilizes the often ignored fact that you can use comma-separated statements for the first and third expressions in the for loop definition list.