I need to split an age into its components where the age is expressed as eg. 27y5m6w2d or any combination of those values. eg. 2w3d or 27d or 5y2d etc. Result has to be up to 4 variables $yrs, $mths, $wks and $days containing the appropriate numeric values.
I can do it with this code but am hoping there is something more efficient:
$pos = strpos($age, 'y');
if ($pos !== false)
list($yrs, $age) = explode('y', $age);
$pos = strpos($age, 'm');
if ($pos !== false)
list($mths, $age) = explode('m', $age);
$pos = strpos($age, 'w');
if ($pos !== false)
list($wks, $age) = explode('w', $age);
$pos = strpos($age, 'd');
if ($pos !== false)
list($days, $age) = explode('d', $age);
If you have a suggestion, please run it in a 10,000 iteration loop and advise the results. The code above runs in an average of 0.06 seconds for 10,000 iterations. I use this code to test:
<?php
$startTime = microtime(true);
// code goes here
echo "Time: " . number_format(( microtime(true) - $startTime), 4) . " Seconds<br>";
echo 'y='.$yrs.' m='.$mths.' w='.$wks.' d='.$days;
?>