开发者

php if elseif statement problem

I have a very simple php program that I am working on for my computer science class but I am having a little trouble with it.

<?php
$numOfCards = '50'; //$_POST['numOfCards'];
$totalCost = 0.00;

if (numOfCards == '20')
{
$totalCost = $numOfCards*3.00;
}
e开发者_运维百科lse if (numOfCards == '50')
{
$totalCost = $numOfCards*2.50;
}
else
{
$totalCost = $numOfCards*2.00;
}

echo "<p>TOTAL COST FOR ".$numOfCards." CARDS: $".$totalCost."</p>";
?>

As you can see, I was originally getting my $numOfCards value from post data but have set it to 50 to prove a point. The issue is that this code as it is should go to the else if statement but instead it is going to the else statement. This results in totalCosts equalling $100 instead of $125.

Does anyone know what I am doing wrong? Thanks


You seem to have a $ missing in numOfCards twice.

To easier find these problems enable error reporting and warnings on top of your script:

error_reporting(-1);
ini_set('display_errors','On');

Then you will see two messages explaining that instead of comparing against a variable (as you wanted to) you compared against the string "numOfCards".


You have to use $numOfCards instead of just numOfCards.

Additionally you should indent your code blocks, preferably with 4-spaces per level:

if ($numOfCards == '20') {
    $totalCost = $numOfCards*3.00;
}
else if ($numOfCards == '50') {
    $totalCost = $numOfCards*2.50;
}
else {
    $totalCost = $numOfCards*2.00;
}


It looks like you are missing the $ in the variable names.

if (**$**numOfCards == '20')

http://ideone.com/Y89nu


Yes you missed a $ sign

The code should be

$numOfCards = '50'; 
//$_POST['numOfCards']; 
$totalCost = 0.00;  

if ($numOfCards  == '20') 
{     
  $totalCost = $numOfCards*3.00;     
} 
else if ($numOfCards  == '50') 
{     
  $totalCost = $numOfCards*2.50;     
} 
else 
{     
  $totalCost = $numOfCards*2.00;     
}  

echo "<p>TOTAL COST FOR ".$numOfCards." CARDS: $".$totalCost."</p>"; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜