Use goto to Avoid if Nesting

Nexmoe November 25, 2018
This article is an AI translation and may contain semantic inaccuracies.

if in flow control is a simple logical condition, but with multiple conditions it’s easy to create deep if nesting. The logic becomes complex and confusing.

Evil nested if

<?php
$a = array(
    'state' => '1',
    'notice' => '注册成功!',
);

if ($_GET['username'] != '') {
    if (strlen($_GET['username']) > 4 or !strlen($_GET['username']) < 11) {
        $name = array('root','admin','GETmaster','master','webmaster','mixcm','administrator','sb','shabi');
        if (!in_array($_GET['username'], $name)) {
            if (preg_match("/^[a-zA-Z\s]+$/", $_GET['username'])) {
                $a['state'] = '0';
                $a['notice'] = '用户名必须为英文!';
            }
        } else {
            $a['state'] = '0';
            $a['notice'] = '非法用户名!';
        }
    } else {
        $a['state'] = '0';
        $a['notice'] = '请输入大于4字符,且小于11个字符的用户名!';
    }

} else {
    $a['state'] = '0';
    $a['notice'] = '用户名不能为空!';
}

echo json_encode($a,JSON_UNESCAPED_UNICODE);

So in real work, we try to avoid this. That’s where goto and table data come in.

  • Clear logic
  • Easy to modify later
  • But avoid overusing goto; recommend only one label. In this example, only end is defined.

Solve with goto (the following code uses table data):

<?php
$a = array(
    'state' => '1',
    'notice' => '注册成功!',
);

if ($_GET['username'] == '') {
    $a['state'] = '0';
    $a['notice'] = '用户名不能为空!';
    goto end;
}

if (strlen($_GET['username']) < 4 or strlen($_GET['username']) > 11) {
    $a['state'] = '0';
    $a['notice'] = '请输入大于4字符,且小于11个字符的用户名!';
    goto end;
}

$name = array('root','admin','GETmaster','master','webmaster','mixcm','administrator','sb','shabi');
if (in_array($_GET['username'], $name)) {
    $a['state'] = '0';
    $a['notice'] = '非法用户名!';
    goto end;
}

if (!preg_match("/^[a-zA-Z\s]+$/", $_GET['username'])) {
    $a['state'] = '0';
    $a['notice'] = '用户名必须为英文!';
    goto end;
}

end:
echo json_encode($a,JSON_UNESCAPED_UNICODE);