Concatenation Help

Hello,

I am new to PHP and am having a bit of trouble with what I am sure is a very simple thing.

I am taking an online course and working on a simple project to build a calculator. What is wrong with this line of code?

echo $_GET[“num1”] . " plus " . $_GET[“num2”] . " equals: " $result1 + $result2;

The problem is with $result1 + $result2

I am trying to get an output like this:

1 plus 2 equals: 3

If I move the $result1 + $result2 down to the next line it seems to work but not when it is on the same line.

Thanks for your help!

Joe

if you use code highlighting, like that which is provided by surrounding php code in code blocks,then you should see that you are missing the last string concatenator:

echo $_GET[“num1”] . " plus " . $_GET[“num2”] . " equals: " . $result1 + $result2;

the final full-stop/period/dot should solve your problem, unless, you haven’t set up the rest of your code without errors.

1 Like

Hi John,

Thanks for the reply.

I did try adding the extra . but now I get this error:

Notice : A non well formed numeric value encountered in C:\xampp\htdocs\sandbox\15.php on line 34

Here is the full code:

<?php
	if (isset($_GET['submit'])) {
		$result1 = $_GET['num1'];
		$result2 = $_GET['num2'];
		$operator = $_GET['operator'];

		switch ($operator) {
			case "None":
				echo "You need to select a method!";
				break;
			case "Add":
				echo $_GET["num1"] . " plus " . $_GET["num2"] . " equals: " . $result1 + $result2;
				echo  $result1 + $result2;
				break;
			case "Subtract":
				echo $result1 - $result2;
				break;
			case "Multiply":
				echo $result1 * $result2;
				break;
			case "Divide":
				echo $result1 / $result2;
				break;	
		}
	}
?>

Start with getting rid of the variables for nothing. As far as what your doing, you need to put parenthesis around the last two variables

echo $_GET["num1"] . " plus " . $_GET["num2"] . " equals: " . ($result1 + $result2);

Thanks Benanamen! The ( )'s were the answer!

Sponsor our Newsletter | Privacy Policy | Terms of Service