开发者

Optimizing PHP code (trying to determine min/max/between case)

I know this code-bit does not conform very much to best coding practices, and was looking to improve it, any ide开发者_如何学Pythonas?

if ($query['date_min'] != _get_date_today())
    $mode_min = true;
if ($query['date_max'] != _get_date_today())
    $mode_max = true;

if ($mode_max && $mode_min)
    $mode = "between";
elseif ($mode_max && !$mode_min)
    $mode = "max";
elseif (!$mode_max && $mode_min)
    $mode = "min";
else
    return;

if ($mode == "min" || $mode == "between") {
    $command_min = "A";
}
if ($mode == "max" || $mode == "between") {
    $command_max = "B";
}
if ($mode == "between") {
    $command = $command_min . " AND " . $command_max;
} else {
    if ($mode == "min")
        $command = $command_min;
    if ($mode == "max")
        $command = $command_max;
}

echo $command;

Solution:

$mode_min = ($query['date_min'] != _get_date_today());
$mode_max = ($query['date_max'] != _get_date_today());

if ($mode_min){
    $command_min = "A";
}
if ($mode_max) {
    $command_max = "B";
}
if ($mode_min && $mode_max) {
    $command = $command_min . " AND " . $command_max;
} else {
    if ($mode_min)
        $command = $command_min;
    if ($mode_max)
        $command = $command_max;
}


Technically your variables are undefined if the condition is not met, so I would just use:

$mod_min = ($query['date_min'] != _get_date_today());
$mod_max = ($query['date_max'] != _get_date_today());

Apart from that, why are you defining the $mode variable, do you need it somewhere else? If not, you can just use $mod_min and $mod_max in your last set of if statements.

For example:

if ($mode == "min" || $mode == "between")

seems to translate to:

if ($mod_min)

Edit: An edit of your last update:

$command_min = "A";
$command_max = "B";

if ($mode_min && $mode_max) {
    $command = $command_min . " AND " . $command_max;
}
elseif ($mode_min){
    $command = $command_min;
}
elseif ($mode_max) {
    $command = $command_max;
} else {
    return;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜