wavix Posted May 15, 2015 Share Posted May 15, 2015 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'; } Link to comment https://forums.phpfreaks.com/topic/296348-avoid-repetitive-code/ Share on other sites More sharing options...
Ch0cu3r Posted May 15, 2015 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 Link to comment https://forums.phpfreaks.com/topic/296348-avoid-repetitive-code/#findComment-1512010 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]; } Link to comment https://forums.phpfreaks.com/topic/296348-avoid-repetitive-code/#findComment-1512017 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.