如果声明为空_Get

时间:2015-08-22 09:43:39

标签: php if-statement get

我正忙着学习PHP。然而,在我控制变量通过的PHP小网站上,我陷入了If语句问题。

每个内部页面链接我都传递了一个变量来控制我从数据库中提取的内容。甚至从其他内部页面链接到我的Index.php页面。问题是index.php页面会出错,因为当您从外部链接输入saite时会出现一个空的_Get问题。有四页。所有其他页面都没有错误,但加载索引页面会出错。

我的代码:

$Section = $_GET['SID'];
if ( $Section == "HOME" ) {
    $SectionTitle = 'Start';
    $SectionID = 'HOME';
}
if ( $Section == "BDIR" ) {
    $SectionTitle = 'Directory';
    $SectionID = 'BDIR';
}
if ( $Section == "ACOM" ) {
    $SectionTitle = 'Accommodation';
    $SectionID = 'ACOM';
}
if ( $Section == "REST" ) {
    $SectionTitle = 'Restaurants';
    $SectionID = 'REST';
}

我需要实现的是当有一个空_Get它必须分配与Home(First If)值相同的值。

我试过了

if (!empty($_GET)) {
    $SectionTitle = 'Start';
    $SectionID = 'HOME';
}

以及其他一些没有运气的变种。

但是我觉得我不在我的联盟中,因为我想知道,如果我的陈述不在其他if语句之内(或之下),我应该有一些吗?

3 个答案:

答案 0 :(得分:2)

$Section = !isset($_GET['SID']) || empty($_GET['SID']) ? 'HOME' : $_GET['SID'];
switch($Section) {
  case "BDIR":
    $SectionTitle = 'Directory';
    $SectionID = 'BDIR';
    break;
  case "ACOM"
    $SectionTitle = 'Accommodation';
    $SectionID = 'ACOM';
    break;
  case "REST":
    $SectionTitle = 'Restaurants';
    $SectionID = 'REST';
    break;
  case "HOME":
  default:
    $SectionTitle = 'Start';
    $SectionID = 'HOME';
    break;
}

答案 1 :(得分:2)

为了不编写许多类似的if语句,我宁愿添加一个数组并通过密钥存在来检查它。 然后像这样定义默认的SectionTitle和SectionID:

<?php

$SectionTitle = 'Start';
$SectionID    = 'HOME';

$sections = [
    'BDIR' => 'Directory', 
    'ACOM' => 'Accommodation',
    'REST' => 'Restaurants'
];

if (!empty($_GET['SID']) && array_key_exists($_GET['SID'], $sections)) {
    $SectionTitle = $sections[$_GET['SID']];
    $SectionID    = $_GET['SID'];
}

答案 2 :(得分:0)

可能这会对你有所帮助。试试这段代码。

 if($_GET)
{
    $Section = $_GET['SID'];
    if ( $Section == "HOME" ) {
        $SectionTitle = 'Start';
        $SectionID = 'HOME';
    }
    if ( $Section == "BDIR" ) {
        $SectionTitle = 'Directory';
        $SectionID = 'BDIR';
    }
    if ( $Section == "ACOM" ) {
        $SectionTitle = 'Accommodation';
        $SectionID = 'ACOM';
    }
    if ( $Section == "REST" ) {
        $SectionTitle = 'Restaurants';
        $SectionID = 'REST';
    }
}
相关问题