PHP 精确到天年龄计算函数实现
代码实现如下所示:
<?php
/**
此 PHP 函数旨在计算用户的年龄。
*
该函数的参数设计灵活,既支持以数组形式传参,也兼容标准的 MySQL date 格式字符串。
以下是参数的使用示例:
* --------------------------------------------------
$birthArr = array(
'year' => '2000',
'month' => '11',
'day' => '3'
);
$birthStr = '2000-11-03';
* --------------------------------------------------
* );
作者:IT不倒翁
版权信息 (c) 2011,2012 Just Use It!
相关链接 IT不倒翁 http://yungbo.com
@param string|array $birthday 接收生日数据,可以是字符串或数组。
@return number $age 返回计算得出的年龄数值。
*/
function getAge($birthday) {
$age = 0;
$year = $month = $day = 0;
if (is_array($birthday)) {
extract($birthday);
} else {
if (strpos($birthday, '-') !== false) {
list($year, $month, $day) = explode('-', $birthday);
$day = substr($day, 0, 2); //获取前两个字符以防格式为 '2000-11-03 12:12:00'
}
}
$age = date('Y') - $year;
if (date('m') < $month || (date('m') == $month && date('d') < $day)) $age--;
return $age;
}