简体   繁体   中英

php, how to simplify a php script?

im not sure this is a good question to post but here is my issue. I have an if statement that is getting way too long and i was wondering if there is some other kind of syntax to shorten it out:

if (($time1 <= $one_day)&&
    ($time2 <= $one_day)&&
    ($time3 <= $one_day)&&
    ($time4 <= $one_day)&&
    ($time5 <= $one_day)&&
    ($time1 != NULL)&&
    ($time2 != NULL)&&
    ($time3 != NULL)&&
    ($time4 != NULL)&&
    ($time5 != NULL)){
    //do sometihng
}

this is one example but i have a similar one that goes up to ..&&($time15 <= $one_day) .

the statement is pretty self explanatory, $time1, $time2, etc can come back empty so i have to check if they are NULL or not

any ideas?

thanks

You can put the common stuff in a function:

function validate_time($time, $one_day) {
    return $time <= $one_day && $time != NULL;
}
if (validate_time($time1, $one_day) &&
    validate_time($time2, $one_day) &&
    validate_time($time3, $one_day) &&
    validate_time($time4, $one_day) &&
    validate_time($time5, $one_day)) {
    // do something
}

You may want to refactor code and eliminate the need for copying & pasting those checks. Another way to get the job done:

while (true) {
    foreach (array($time1, $time2, $time3, $time4, $time5) as $time) {
        if ($time > $one_day || $time == NULL) {
            break 2;
        }
    }
    // do something
    break;
}

The above could be put in a function as well which would make the while-loop and break keyword redundant. Replace break 2 by return then.

Using an array for you variables would help. The you can iterate over them and check.

将时间放在数组中并使用for循环进行检查。

不要使用15个相似但不同的变量,而应考虑使用数组。

If you must (or want to) keep the original variable names and not use an array here is the good solution (for $time1 to $time5):

$ok = true;
for ($i = 1; $i <= 5; $i++)
{
    $var =& ${'time'.$i};
    if ( ! ($var <= $one_day && $var != NULL))
    {
        $ok = false;
    }
}

if ($ok)
{
    //do something
}

您可以将所有值设置为一个数组,并使用For循环进行比较。

A functionised version which should help with your reuse. This is similar to Lekensteyns code.

$times = array(
    'time',
    'time',
    'time',
    'time',
    'time',
);

function validateTime($checks, $limit) 
{
    foreach($checks as $check) {
        if($check == null || $check > $limit) {
            return false;
        }
    }
    return true;
}

if(validateTime($times,$one_day) == true) {
  //codey code.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM