Jump to content

Avoid repetitive code


Go to solution Solved by Ch0cu3r,

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';
}
Edited by wavix
Link to comment
https://forums.phpfreaks.com/topic/296348-avoid-repetitive-code/
Share on other sites

  • Solution

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];
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.