这个IF声明有什么问题

时间:2014-11-15 00:44:26

标签: php if-statement

我试图让它显示正确的东西。当我运行它时,酒店的费用保持在960美元,如果我选择开罗,它将显示0美元的航空公司机票,酒店是960美元。其他工作正常,但不会从960美元改变酒店成本。

if ($destination == "Barcelona")

    $airFare = 875;
    $hotel = 85 * $numNights;

    if ($destination == "Cairo")
    $airfare = 950;
    $hotel = 98 * $numNights;

    if ($destination == "Rome")
    $airFare = 875;
    $hotel= 110 * $numNights;

    if ($destination == "Santiago")
    $airFare = 820;
    $hotel = 85 * $numNights;

    if ($destination == "Tokyo")
    $airFare = 1575;
    $perNight = 240;

    $tickets = $numTravelers * $airFare;
    $hotel = $numTravelers * $numNights * $perNight;
    $totalCost = $tickets + $hotel;

    print("<p>Destination: $destination<br />");
    print("Number of people: $numTravelers<br />");
    print("Number of nights: $numNights<br />");
    print("Airline Tickets: $".number_format($tickets, 2)."<br />");
    print("Hotel Charges: $".number_format($hotel, 2)."</p>");
    print("<p><strong>TOTAL COST: $".number_format($totalCost, 2)."</strong></p>");

2 个答案:

答案 0 :(得分:1)

一些问题:

  • 红衣主教罪:你在没有缩进的情况下使用无支撑if语句,因此不清楚你的意图是什么。为了安全起见:总是使用if的大括号,除非它只是一行!这就是今年早些时候苹果公司发布的关键OpenSSL漏洞的原因。
  • $numNights未定义,未定义的数字默认为PHP中的0。任何零的乘积都是......零。因此,当您的计算涉及$numNights时,您的计算错误的原因。
  • 您已将$字符嵌入双引号字符串中,这意味着PHP将尝试为变量名称解析这些字符串。使用\$转义符号或使用单引号字符串。

答案 1 :(得分:0)

<?php
$destination = "Cairo";
$numNights = (int)10;
$airFare = (int)1000;
$numTravelers = (int)2;
$perNight = (int)49;

if ($destination == "Barcelona")
{
    $airFare = 875;
    $hotel = 85 * $numNights;
}

if ($destination == "Cairo")
{
    $airfare = 950;
    $hotel = 98 * $numNights;
}

if ($destination == "Rome")
{
    $airFare = 875;
    $hotel= 110 * $numNights;
}

$tickets = $numTravelers * $airFare;
$hotel = $numTravelers * $numNights * $perNight;
$totalCost = $tickets + $hotel;

print("<p>Destination: $destination<br />");
print("Number of people: $numTravelers<br />");
print("Number of nights: $numNights<br />");
print("Airline Tickets: $".number_format($tickets, 2)."<br />");
print("Hotel Charges: $".number_format($hotel, 2)."</p>");
print("<p><strong>TOTAL COST: $".number_format($totalCost, 2)."</strong></p>");

&GT;