2008-09-20

Calculate Age: One-Liner Fun

by Charles — Categories: PHP — Tags: , 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.

1 Comment »

  1. nrg_alpha says:

    Nice little script. Does indeed remind the rest of us that you can have multiple first and third comma-separated statements. I never made use of this, but can see where it streamlines things.

Leave a Reply

© 2012 PHP Musings All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!