开发者

PHP function running inside loop not working (with code)

I am running this function

function Age($month, $day, $year) {
    date_default_timezone_set('America/New_York');
    $dob = $month .''. $day .''. $year;
    $startDate = strtotime($dob);
    $endDate = time();
    $dif = $endDate - $startDate;

    return $years = (date('Y', $dif) - 1970) .' y, '. ($months = date('n', $dif) - 1).' m';
}

inside a foreach loop (some CodeIgniter markup):

foreach ($users as $row) {
    echo $this->includes->Age($row->birth_month, $row->birth_day, $row->birth_year)开发者_运维知识库
  }

The loop works OK, showing all my users.

But the problem is that it calculates the age correctly for the first user and then shows that same age for all other users. I should point out that all other user's data is correct, only the age is wrong.

Anyone know how to fix this?

Thanks!


Your $dob looks malformed. Try $dob = $year . '-' . $month . '-' $day;


You're missing space/separators.

$dob = $month .''. $day .''. $year;

should be

$dob = $month .'/'. $day .'/'. $year;

edit: Ambiguity. If using mm-dd-yyyy format, should be /

. and - indicate dd-mm-yyyy


Maybe CI is caching the result?
Seems that function Age is correct

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜