wavix Posted May 15, 2015 Share Posted May 15, 2015 (edited) Is there any other way to get this? $oneTime = preg_replace('/[^0-9]/', '', $one); $twoTime = preg_replace('/[^0-9]/', '', $two); $threeTime = preg_replace('/[^0-9]/', '', $three); if($oneTime == '') { $oneTime = '1 month'; } if($oneTime == '7') { $oneTime = '7 days'; } if($oneTime == '24') { $oneTime = '24 hours'; } if($twoTime == '') { $twoTime = '1 month'; } if($twoTime == '7') { $twoTime = '7 days'; } if($twoTime == '24') { $twoTime = '24 hours'; } if($threeTime == '') { $threeTime = '1 month'; } if($threeTime == '7') { $threeTime = '7 days'; } if($threeTime == '24') { $threeTime = '24 hours'; } Edited May 15, 2015 by wavix Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted May 15, 2015 Solution Share Posted May 15, 2015 If you find you are repeating code then its time to refactor the code into a function, example code function getTimePeriod($value) { $value = preg_replace('/[^0-9]/', '', $value); if($value == '') { $value = '1 month'; } elseif($value == '7') { $value .= ' days'; } elseif($value == '24') { $value .= ' hours'; } return $value; } $oneTime = getTimePeriod($one); $twoTime = getTimePeriod($two); $threeTime = getTimePeriod($three); For more information on writing your own functions go to http://php.net/manual/en/functions.user-defined.php Quote Link to comment Share on other sites More sharing options...
kicken Posted May 16, 2015 Share Posted May 16, 2015 Since your code is essentially mapping one value to another, you could also use an array with a key=>value map. function getTimePeriod($value){ $map = [ '' => '1 month' , '7' => '7 days' , '24' => '24 hours' ]; $value = preg_replace('/[^0-9]/', '', $value); return $map[$value]; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.