Jump to content

Avoid repetitive code


wavix

Recommended Posts

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

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

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];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.