简单的循环不起作用

时间:2012-11-09 22:50:29

标签: php if-statement

我正在从一个给我团队名称的地方剪切信息。如果我echo $HomeTeam;,我会得到“Man Utd”的值。

但是当我这样做时......它不起作用(显示空白)。

$PlayerName = "Robin Van Persie"; //just to test that it's working
switch($PlayerName)
    {
    case "Robin Van Persie":
        if ($HomeTeam == "Man Utd") { echo $HomeTeam; } 
        break;
    default: echo "Player not in the list"; break;
    }

这显示为空白......任何想法为什么?我尝试添加$HomeTeam = strval($HomeTeam);将其转换为字符串,但没有任何区别。

4 个答案:

答案 0 :(得分:0)

$HomeTeam变量未设置,这就是打印时返回空的原因。将值设置为这样的&它应该工作。

$PlayerName = "Robin Van Persie"; //just to test that it's working
$HomeTeam = "Man Utd";
switch($PlayerName)
    {
    case "Robin Van Persie":
        if ($HomeTeam == "Man Utd") { echo $HomeTeam; } //Man Utd
        break;
    default: echo "Player not in the list"; break;
    }

答案 1 :(得分:0)

你有if ($HomeTeam == "Man Utd")没有其他设置发生,所以$ HomeTeam不能等于"Man Utd"

答案 2 :(得分:0)

试试这个

$PlayerName = "Robin Van Persie"; //just to test that it's working
switch($PlayerName){
    case "Robin Van Persie":
        $HomeTeam ?  print($HomeTeam) : print("HomeTeam is not set");
    break;
    default: echo "Player not in the list"; break;
}

答案 3 :(得分:0)

如果您要硬编码并且不将值存储在数据库中,那么使用数组的方法会让您感兴趣:

$search = "Robin Van Persie";

//Your data array, easyier to add to no
$teams = array(
    'Manchester United'=>array('Robin Van Persie',
                               'Wayne Rooney',
                               ),

    'Arsenal'=>array('Theo Walcott',
                     'Nicklas Bendtner',
                     ),             
);

$result=null;
foreach($teams as $team=>$players) {
    if(in_array($search,$players)) {
        $result = $team;
    }
}
//Robin Van Persie's team is Manchester United
echo ($result != null) ? $search.'\'s team is '.$result : 'Team for '.htmlentities($search).' not found.';