Consider the following line of code:
<?php
$x = 10;
$y = 7;
echo '10 - 7 = '.$x-$y;
?>
The output of that is 3, which is the expected result of the calculation $x-$y. However, the expected output is:
10 - 7 = 3
My question therefore is, what happened to the string that I'm concatenating with the calculation? I know that in order to produce the result I expected, I need to enclose the arithmetic operation in parenthesis:
<?php
$x = 10;
$y = 7;
echo '10 - 7 = '.($x-$y);
?>
outputs
10 - 7 = 3
But since PHP does not complain about the original code, I'm left wondering what the logic behind the produced output in that case is? Where did the string go? If anyone can explain it or point me to a location in the PHP manual where it is explained, I'd be grateful.
Your string '10 - 7 = ' is being concatenated with $x. Then that is being interpreted as an int which results in 10 and then 7 is subtracted, resulting in 3.
For more explanation, try this:
echo (int) ('10 - 7 = ' . 10); // Prints "10"
More information on string to number conversion can be found at http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
If the string starts with valid numeric data, this will be the value used
In this code:
echo '10 - 7 = '.$x-$y;
The concatenation takes precedence, so what you're left with is this:
echo '10 - 7 = 10'-$y;
Because this is trying to perform integer subtraction with a string, the string is converted to an integer first, so you're left with something like this:
echo (int)'10 - 7 = 10'-$y;
The integer value of that string is 10, so the resulting arithmetic looks like this:
echo 10-$y;
Because $y is 7, and 10 - 7 = 3, the result being echoed is 3.
. and - have the same precedence, so PHP is reinterpreting '10 - 7 = 10' as a number, giving 10, and subtracting 7 gives 3.
PHP runs operations in the order defined here ; https://www.php.net/manual/en/language.operators.precedence.php
Take a look at this example ;
$session_period = 30;
new \DateTime('now -' . $session_period+1 . ' minutes');
Beware! This will NOT give you the time 31 minutes ago.
In this case PHP just interprets starting from the leftmost part of an expression so this simple-looking expression returns the wrong result;
Because ;
'now -' . $session_period => 'now -30'
then PHP will cast the string to 0 and add 1 to that => 1
and 1 . ' minutes' => '1 minutes'
That's why the expression above will give you the result of
new \DateTime('1 minutes')
To avoid this kind of confusion, use () like this ;
new \DateTime('now -' . ($session_period+1) . ' minutes');
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
I am learning to work with some math like PHP query and just got to the modulo, I am not quite sure in what situations to use this because of something i stumbled on and yes I did already read one of the posts here about the modulo :
Understanding The Modulus Operator %
(This explanation is only for positive numbers since it depends on the language otherwise)
The quote above is in the top answer there. But if I focus on PHP only and i use the modulo like this:
$x = 8;
$y = 10;
$z = $x % $y;
echo $z; // this outputs 8 and I semi know why.
Calculation: (8/10) 0 //times does 10 fit in 8.
0 * 10 = 0 //So this is the number that has to be taken off of the 8
8 - 0 = 8 //<-- answer
Calculation 2: (3.2/2.4) 1 //times does this fit
1 * 2.4 = 2.4 //So this is the number that has to be taken off of the 3.2
3.2 - 2.4 = 0.8 // but returns 1?
So my question is why does this exactly happen. my guess would be that in the first phase it would get 8/10 = 0,8 but this doesn't happen. So can someone explain a bit about why this happens. I understand the modulo's basics like if I do 10 % 8 = 2 and I semi understand why it doesn't return something like this: 8 % 10 = -2.
Also, is there a way to modify how the modulo works? so it would return a - value or a decimal value in the calculation? or would I need to use something else for this
Little shortened: why does this happen when I get a negative number in return and is there some other way or operator that can actually do the same and get in the negative numbers.
Modulus (%) only works for integers, so your calculation at the bottom of your example is correct...
8/10 = 0 ( integer only ), remainder = 8-(0*10) = 8.
If you instead had -ve 12 - -12%10...
-12/10 = -1 (again integer only), remainder = -12 - (10*-1) = -2
For floats - you can use fmod(http://php.net/manual/en/function.fmod.php)
<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
(Example from manual)
I'm currently learning PHP from a HTML, CSS, and JS background and I came across some unexpected behavior that interested me. Consequently, I experimented with the following code.
Experiment 1:
It seems that when written the return statement is written like this, everything before the arithmetic is removed/not rendered.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
17<br>
21<br>
Experiment 2:
However, when I change the first variable/parameter from $num to $num2, it seems that every between the first variable and the + operator is removed.
Code:
<?php
function add($num, $num2) {
return $num2."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
14<br>
2<br>
Experiment 3:
After trying it in JS, I realized that putting brackets around the arithmetic equation would output the expected result.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".($num + $num2)."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
10+7 = 17<br>
20+1 = 21<br>
(Also making a $sum variable would fix the problem)
Question:
My question is what causes the unexpected behavior by not putting the brackets around the equation?
The behavior you are seeing is the result of "type juggling".
Because PHP is not strictly-typed, a string can be interpreted as an integer when needed (or assumed to be needed by the interpreter), or vice versa. So the data type is converted, and if you're not careful can cause issues. In many other languages you would get an error if you treated a string like an integer or an integer like a string. JavaScript, for example, has String.parseInt() to explicitly change the type.
What the interpreter is doing is roughly the following, step-by-step:
$num - establish an integer with value 10
10."+" - concatenating an integer with a string
Convert the current output to a string (10 becomes "10"), and append a plus sign
Output is now "10+"
"10+".$num2 - concatenating a string with an integer
Convert the integer to a string and append it
Output is now "10+7"
"10+7"." = " - concatenating 2 strings
Output is now "10+7 = "
"10+7 = ".$num - concatenating a string with an integer
Convert the integer to a string and append it
Output is now "10+7 = 10
"10+7 = 10" + $num2 - arithmetic calculation between a string and an integer
Convert the string to an integer and add it to the next integer.
In this case, when PHP converts a string to an integer, it starts at the beginning of the string and returns all numerals until it hits the first non-number, so "10+7 = 10" pulls out the 10, then hits the + and stops looking for numbers.
Output is now 17;
17."<br>" - concatenation of an integer and a string
Convert the integer to a string and append the <br>
Output is now 17<br>.
For reference:
Documentation on type juggling: http://php.net/manual/en/language.types.type-juggling.php
How does PHP know that you don't want to take this $num."+".$num2." = ".$num and arithmetically add it to this $num2."<br>"? It doesn't, unless you use parentheses to cause the $num + $num2 to happen first.
In the first example:
$num."+".$num2." = ".$num
Equates to the string: 10+7=10, and then:
$num2
Equates to 7.
When you attempt to add them + the string 10+7=10 must be cast to an integer 10 and and when added to 7 gives you 17 then the string <br> is concatenated.
See PHP: String Conversion to Numbers
With parentheses:
$num."+".$num2." = ".($num + $num2)."<br>";
You get string 10+7= concatenated with 10+7 (17) concatenated with string <br>.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Consider:
php > echo '1 + 5' * '42 + 1' . "\n";
42
I was expecting some sort of error or warning, but PHP lets us multiply strings without complaint. However, why does it display the first integer from the second string?
Some more examples, for which I can find no real logical reason behind the results:
php > echo '1 hi' * '42 + 1' . "\n";
42
php > echo 'hi' * '42 + 1' . "\n";
0
php > echo '1 + 5' * '42 + hi' . "\n";
42
php > echo '1 + 5' * '42 hi' . "\n";
42
php > echo '1 + 5' * '42hi' . "\n";
42
PHP tries to convert the strings to numbers on the fly and does the math based on what it gets. When a string starts with a non-number it is converted to a zero - hence your answers.
When PHP converts these, it is done in a left to right fashion:
The string 1 + 5 actually converts to the number 1 - then the 42 + 1 converts to 42. Your statement is therefore 1 * 42 and the result is an echo of 42. The statement you have with the zero answer, you try to multiply hi (which is cast as zero) and therefore you get a result of zero.
Edit: As for why it is echo'ing out the answer rather than the strings - that's simply due to operator precedence. Math operators are ranked higher than string operators - so it treats it as something it should work out then echo over something it should echo out as it stands.
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';