【问题标题】:Why wont this php if statement work?为什么这个 php if 语句不起作用?
【发布时间】:2014-02-23 05:20:12
【问题描述】:

我有一个名为 $type 的变量,即 type1 或 type2。我有另一个名为$price 的变量,我想根据$type 变量的内容进行更改。由于某种原因,在发送的电子邮件中,什么都没有。我已经将$price 设置为 if 之外的一些随机文本,然后我就可以工作了,所以我知道这不是邮件功能。有人知道为什么这个 if 语句不起作用吗?

PHP

$type = "type 2";

if( $type == "type1" ) $price = "249 kr";
if( $type == "type2" ) $price = "349 kr";


$headers = 'From: xxxxxx@gmail.com';
$subject = 'the subject!';
$message = $price; 

mail($email, $subject, $message, $headers);

谢谢

顺便说一句,在人们生气之前,我一直在搜索和关注一些东西,但没有任何效果。

编辑 正确的做法是:

$type = "type 2";

    if( $type == "type1" ) $price = "249 kr";
    else                   $price = "349 kr";


    $headers = 'From: xxxxxx@gmail.com';
    $subject = 'the subject!';
    $message = $price; 

    mail($email, $subject, $message, $headers);

谢谢玛雅

【问题讨论】:

  • 您的代码中的$type 设置在哪里?你确定字符串中没有空格吗?你试过转储变量来看看你有什么吗?
  • 您是否通过var_dump($type) 来查看您正在处理的问题?
  • “我一直在搜索和关注一些东西,但没有任何效果。”更加详细一些。你遵循的这些“东西”是什么?
  • 抱歉不够具体。 j08691: $type 在代码中设置得更靠前一点。 Gabirel:对不起,我的意思是我已经搜索过试图找出它为什么不起作用但找不到答案。现在得到了答案。还是谢谢

标签: php string if-statement assign


【解决方案1】:

如果$type只能是“type1”或“type2”,你应该这样写:

if( $type == "type1" ) $price = "249 kr";
else                   $price = "349 kr";

如果现在价格显示为“349 kr”,则您在$type 中的值可能有误。

你也应该考虑

 if( $type == "type1" ) $price = "249 kr"; else
 if( $type == "type1" ) $price = "349 kr";
 else                   $price = "error"; 

【讨论】:

  • 请不要以这种风格(水平)编写代码,并始终放置{ },以确保您不会错过任何超出应有的IF。
  • 在你的第二个例子中,$type == "type1" 不应该是$type == "type2"吗?
  • 你应该考虑调用:error_reporting(E_ALL);
【解决方案2】:

鉴于您的帖子,我唯一能想象的是$type 没有"type1" 或"type2",因此永远不会分配$price,因为IF 语句不正确。

你可以的

if( $type === 'type1' ) {
  $price = 'something';
}
else {
  $price = 'something default';
}

所以至少它总是会分配一些东西。

此外,您还可以检查 $type 中的内容,以及 var_dump($type)

【讨论】:

    【解决方案3】:

    你应该检查 $type isset 与否:

    $price='';
    if( isset($type) ){
     if( $type == "type1" ) $price = "249 kr";
     if( $type == "type2" ) $price = "349 kr";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多