1

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;
}
else 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

4 Answers 4

5

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Curious: What's the logic behind CW?
@mellamokb I don't like that pointing out a missing $ gains so much reputation. I'm trying this out for questions that are either about a totally trivial manual link (background here) or a small typo
Thanks for all of the advice. I'm used to C# where simple errors like this would come up at compile time. I guess I'll have to pay more attention with php :(
2

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;
}

Comments

0

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

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

http://ideone.com/Y89nu

Comments

-1

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>"; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.