hybridgoomba Posted June 7, 2008 Share Posted June 7, 2008 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 More sharing options...
Jesdisciple Posted June 7, 2008 Share Posted June 7, 2008 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 More sharing options...
hybridgoomba Posted June 7, 2008 Author Share Posted June 7, 2008 It worked, thanks. But...I didn't put parentheses around the numbers when I was doing addition, division, multiplication, and modulus though. Is "-" something special? Link to comment Share on other sites More sharing options...
Jesdisciple Posted June 7, 2008 Share Posted June 7, 2008 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 More sharing options...
hybridgoomba Posted June 7, 2008 Author Share Posted June 7, 2008 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.