Where does the '42' come from? [closed] - php

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.

Related

php: why 14 + ' ' + 12 returns 26? [duplicate]

This question already has answers here:
Adding string with number in php
(6 answers)
Closed 2 years ago.
I'm a beginner in PHP. with my experience something like "number + String + number" should be a string.
But apparently, it's a number in php.
in my case:
echo 14 + ' ' + 12;
// returns 26
// expected: "14 12"
why did this happen?
and how to fix it?
You are adding a '+' for adding two numbers. These are not a string so it will do a addition.
Use this if you want to add these couple of number as a couple of string :-
echo '14'.' '.'12';
// result "14 12";
You can also use with a html code for a blank space :
echo '14&nbsp12';
// result "14 12";
Because echo accepts parameters only inside quotes. If you want text being returne use:
echo"14 12";
In you case PHP does 2 things
Takes 14 adds to 12
Concatenates space.

PHP echo with int values [duplicate]

This question already has answers here:
PHP string number concatenation messed up
(5 answers)
Closed 4 years ago.
To keep it short, why does
<?php
$var = 'Calc: ' . 5 - 5 . '!';
echo $var;
?>
output:
-5!
Instead of, let's say:
Calc: 0 . '!'
Or another variation of this problem:
<?php
echo "time is" . time()-2;
?>
Prints:
-2
Notice the corruption, the first "string" with the first int is chopped off!
Though, < $var = 'Calc: ' . (5 - 5) . '!'; > (does work ok), I'm trying to understand what the key concept behind this behavior is.
Good old math comes and saves the day.
Adding () means it will be calculated first and give you a correct string.
$var = 'Calc: ' . (5 - 5) . '!';
echo $var; //Calc: 0!
https://3v4l.org/p8OYf

PHP value comparison wrong despite correct typing [duplicate]

This question already has answers here:
Compare floats in php
(17 answers)
Closed 4 years ago.
This piece of code:
$total=$o->cart->getTotalSum();
$subTotal=$o->cart->getSubTotal();
if(floatval($r['sum_total']) != floatval($total) ||
floatval($r['sum_sub']) != floatval($subTotal)) {
echo 'Differs on #' . $r['id'];
echo 'Total: ' . $total . ' / ' . $r['sum_total'];
echo 'Sub: ' . $subTotal . ' / ' . $r['sum_sub'];
}
Gives me this output:
Differs on #697
Total: 19.6 / 19.6
Sub: 19.6 / 19.6
Why? How is that even possible?
I make sure that all values compared are of type float, so no strings could have slipped in.
I must be missing something.
My apologies for not providing really reproducible code, but i wouldn't know how in this case.
If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which
seem to result in the same value do not need to actually be identical.
So if $a is a literal .17 and $b arrives there through a calculation
it can well be that they are different, albeit both display the same
value.
Usually you never compare floating-point values for equality like
this, you need to use a smallest acceptable difference:
if (abs(($a-$b)/$b) < 0.00001) { echo "same"; } Something like that.
I think someone else had the exact same problem.
https://stackoverflow.com/a/3148991/2725502

PHP echo, how it's produce the output? [duplicate]

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;
?>

Arithmetic operation within string concatenation without parenthesis causes strange result

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');

Categories