简体   繁体   中英

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; $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM