Jump to content

Subtraction operator help


hybridgoomba
 Share

Recommended Posts

I was writing my first PHP script today and I came across a problem when I was practicing with the subtraction operator.Right, so when I typed a line like this:

echo 6 - 2;

It displayed the result "4". Wonderful, right?but when I tried putting it in a string:

echo "text ". 6 - 2;

I got the result "-2". I'm not sure why it's not working, so any help would be welcome.

Link to comment
Share on other sites

I think strings are evaluated as 0 when treated as numbers, and 6 will be concatenated to "text" before 2 is subtracted. Try this:

echo "text ". (6 - 2);

EDIT: See http://www.php.net/manual/en/language.oper...tors.precedence

Link to comment
Share on other sites

Did you put the numbers before the string in those cases? Concatenation and arithmetic operators are evaluated left-to-right. (In case you didn't catch my edit, see http://www.php.net/manual/en/language.oper...tors.precedence)

Link to comment
Share on other sites

You know what, here's the whole script so far:

<?php//These are variables, and this is a single-line comment$hello = "What's Up?";$hi = "My name is: ";$br = "<br>";$addition = 2+4;$answers = "correct";$subtraction = 6 - 2; /*This is a multi-line comment, and below this is all of my 'body' code*/echo $hello." ".$hi."Bobby Joe Jr.".$br;echo "Hello World!";echo $br."Escaping quotes \" is fairly \" easy".$br;echo "Perform Addition: 2 + 4 = ".$addition;echo $br;echo "text ". (6 - 2);echo $br;echo "HaHa, getting smarter are we? 4 * 6 = ". 4*6 .$br;echo " How have you made it this far? Last test: 8 / 2 = ". 8/2 .$br;echo "OK, maybe I lied. But still- Modulus, The Final Boss! 5 % 2 = ". 5%2 .$br;echo $br.$br;if ( $answers == "correct" ) {  echo "I, I don't believe it... I feel the powers of light overtaking my soul already...".$br."Or, in other words, you beat the game, first PHP script ever!";}echo $br;echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />"; ?>

Ignore the weird text I put in there. I had to have some fun with it, you know...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...