I was experimenting with weak/dynamic typing properties of PHP in preparation for a test and was completely baffled by the output of this string concatenation. Can someone explain how this is even possible?
<?php echo 1 . "/n" . '1' + 1 ?><br />
output:
2
Analysis:
echo 1 . "/n" . '1' + 1;
is equivalent to
//joined first 3 items as string
echo "1/n1"+1;
is equivalent to
//php faces '+' operator, it parses '1/n1' as number
//it stops parsing at '/n' because a number doesn't
//contain this character
echo "1"+1;
is equivalent to
echo 1+1;
Related
I'm learning basics in php, and I was trying to add multiple arguments in echo command. But the variable after <br> is not showing.
$number1=10;
echo "number 1 is: ".$number1."<br>";
$number2=20;
echo "number 2 is: ".$number2;
echo "<br> ".$number1+$number2;
and the output should be:
number 1 is: 10
number 2 is: 20
30
But the output is:
number 1 is: 10
number 2 is: 2020
So what's the error?
used this code
$number1=10;
echo "number 1 is: ".$number1."<br>";
$number2=20;
echo "number 2 is: ".$number2;
$total= $number1+$number2;
echo "<br> ".$total;
?>
The output will be:
number 1 is: 10
number 2 is: 20
30
The other answers just state a solution, this answer explains whats happening and how to prevent the unexpected behavior in 2 ways.
The dot operator has the same precedence as + and -.
Considering
$number1 = 10;
$number2 = 20;
echo "<br> ".$number1+$number2;
The dot you've used is a string operator, not a numeric operator.
What's happening:
"<br>" and 10 are concatenated with the dot operator to "<br>10".
"<br>10" is added to $number2 (20) with the numeric + operator.
Non-empty, non-numeric strings are converted to 0. Meaning "<br>10" = 0.
0+20 results in 20 which makes line 3: echo 20;
This can be solved by changing the precedences by using brackets echo "<br> ". ($number1 + $number2); or the less seen option, by passing more arguments to the echo language construct: echo "<br> ", $number1 + $number2; (Note the comma instead of a dot). Each argument will be evaluated first before outputting them all together.
Personally I use the second option (multiple arguments) in cases like this.
Just add the braces to the sum operation.
$number1=10;
echo "number 1 is: ".$number1."<br>";
$number2=20;
echo "number 2 is: ".$number2;
echo "<br> ".($number1+$number2);
The output will be:
number 1 is: 10
number 2 is: 20
30
You should revise code within bracket
echo "<br> ". ($number1 + $number2);
to get the result you want.
Reason: each operation has precendence level
Get reference: http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
This question already has answers here:
Concatenation with addition in it doesn't work as expected
(2 answers)
Closed 7 years ago.
Please explain how echo understand the dot(.) with mathematical expressions and binary comma(,).
<?php
echo "The Sum: " . 2+3;
?>
//Output
3
Why 3 as output?
. and + are left-associative, so your statement is interpreted as
echo ("The Sum: " . 2) + 3;
This is equivalent to
echo "The Sum: 2" + 3;
When you add a string and a number, it converts the string to a number, which tries to find a number at the beginning of the string. Since "The Sum: 2" doesn't begin with a number, it converts to 0. So that makes the statement equivalent to
echo 0 + 3;
which simplifies to
echo 3;
and that's the result you see.
there is two operator dot(.) and plus(+) and dot has high priority so . try this
<?php
echo ("The Sum: " . 2) + 3;
?>
I have a really weird problem: Below in the code listed 4 echo's are pretty much the same, but only the last ones work properly (First two echoes only print the answer of addition/ subtraction, no text).
Here's the code:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?><br>
<?php $sk1 = $_POST["sk1"];
$sk2 = $_POST["sk2"];
$veiksm = $_POST["veiksmas"];
switch($veiksm){
default:
echo "Jus nepasirinkote veiksmo";
break;
case "sud":
echo "Sudeties veiksmo rezultatas: " .$sk1 + $sk2;
break;
case "ati":
echo "Atimties veiksmo rezultatas: " .$sk1 - $sk2;
break;
case "dal":
echo "Dalybos veiksmo rezultatas: " .$sk1 / $sk2;
break;
case "dau":
echo "Daugybos veiksmo rezultatas: " .$sk1 * $sk2;
break;
}
?>
</body>
</html>
You have to put brackets around your calculation like:
echo "Atimties veiksmo rezultatas: " . ($sk1 - $sk2);
//^ See here ^
Otherwise you can imagine your echo statement like this:
"Sudeties veiksmo rezultatas: 17" + 5 // Same as 0 + 5, because the string is casted to int which is 0
Also * and / works because they are getting evaluated first
Put parentheses around the calculation, like this:
echo "Sudeties veiksmo rezultatas: " . ($sk1 + $sk2);
The reason for this is the order in which the expression is processed. Without parentheses, PHP evaluates everything from left to right, so it will first concatinate $sk1 to the string. The combined value will be "Sudeties veiksmo rezultatas: 1" (if $sk1 is 1).
After that, $sk2 is added to that value. Because PHP cannot add up a string, it tries to convert it to a number. This conversion fails, because the string starts with a non-numeric text, and defaults to 0 which is added to the value of $sk2.
Multiplication and division operators have higher precedence, so they are evaluated first, overriding the left-to-right order. That's why it works for the last two cases.
I got some PHP code here:
<?php
echo 'hello ' . 1 + 2 . '34';
?>
which outputs 234,
But when I add a number 11 before "hello":
<?php
echo '11hello ' . 1 + 2 . '34';
?>
It outputs 1334 rather than 245 (which I expected it to). Why is that?
That's strange...
But
<?php
echo '11hello ' . (1 + 2) . '34';
?>
or
<?php
echo '11hello ', 1 + 2, '34';
?>
fixes the issue.
UPDATE v1:
I finally managed to get the proper answer:
'hello' = 0 (contains no leading digits, so PHP assumes it is zero).
So 'hello' . 1 + 2 simplifies to 'hello1' + 2 is 2. Because there aren't any leading digits in 'hello1' it is zero too.
'11hello ' = 11 (contains leading digits, so PHP assumes it is eleven).
So '11hello ' . 1 + 2 simplifies to '11hello 1' + 2 as 11 + 2 is 13.
UPDATE v2:
From Strings:
The value is given by the initial portion of the string. If the string
starts with valid numeric data, this will be the value used.
Otherwise, the value will be 0 (zero). Valid numeric data is an
optional sign, followed by one or more digits (optionally containing a
decimal point), followed by an optional exponent. The exponent is an
'e' or 'E' followed by one or more digits.
The dot operator has the same precedence as + and -, which can yield unexpected results.
That technically answers your question... if you want numbers to be treated as numbers during concatenation, just wrap them in parentheses.
<?php
echo '11hello ' . (1 + 2) . '34';
?>
You have to use () in a mathematical operation:
echo 'hello ' . (1 + 2) . '34'; // output hello334
echo '11hello ' . (1 + 2) . '34'; // output 11hello334
You should check the PHP type conversion table to get a better idea of what's happening behind the scenes.
If you hate putting operators in between, assign them to a variable:
$var = 1 + 2;
echo 'hello ' . $var . '34';
Is this behaviour correct in PHP?
<?php echo '-' . 1 + 1 . ' crazy cats'; ?>
// Outputs:
0 crazy cats
I understand that minus is being concatenated to the first '1' and '-1' casted to integer, and not '2' to string.
Please explain why.
What is the best way to solve it?
This one?
<?php echo '-' . (string)1 + 1 . ' crazy cats'; ?>
First of all, it is correct, and if it would be different it would also be correct, that's how PHP developers defined operand precedence.
In this scenario, no operand has precedence, so u read it left to right
'-' . 1 ==> '-1'
'-1' + 1 ==> 0 (arithmetic operations on strings, will try to cast them to numbers first and then do the arithmetics).
0 . ' crazy cats' ==> "0 crazy cats" (strings operations on numbers, will cast them to strings).
If you want -2 crazy cats, you can set the manipulate precedence with parenthesis:
echo '-' . (1 + 1) . ' crazy cats';
echo also follows the construct of echo 'foo', 'bar' which separates the items into distinct statements to echo. You don't have to worry about concatenation order in that case.
So you could do <?php echo '-', (1 + 1), ' crazy cats'; ?> and your cats wouldn't care about negatives!
If you prefer, this avoids precedence:
printf('-%d crazy cats',1+1);
Your verbiage is off. The '-' is not being casted but concated.
PHP will still treat (string) 1 and -1 as an integer.
. and +/- have the same precedence in PHP, so the string can be read from left to right.
The above is similar to saying:
echo '-1' + '1 crazy cats';