[Solved] Is the result of a print or echo a string or can they be number values in php? [closed]


PHP is giving you the string representation of 10, which is also 10. However, your JS code embeds this inside quotes, making it a JS string value. Since the .value property of the input element is also a string, JS ends up comparing the two “numbers” as strings and probably giving you unexpected results.

Consider that in JavaScript:

2 > 10       ===> false (numeric comparison)
"2" > 10     ===> false ("2" converted to number)
2 > "10"     ===> false ("10" converted to number)
"2" > "10"   ===> true (string comparison!)

If you want to compare numbers, then at least one of the two operands to the comparison must be a number.

To convert the .value to a number, use parseInt:

var s = parseInt(document.getElementById("test").value, 10);

To convert the PHP variable to a number, you can simply lose the quotes around the PHP echo:

onclick="isLarge(<?php print $num?>)"

However this could result in a parse error if $num is not a number. It would be much better to use the bulletproof solution: json_encode to make sure that the value of $num safely transitions into JS-land, and then parseInt to make it a number:

onclick="isLarge(parseInt(<?php print json_encode($num);?>, 10))"

With the above technique, the worst case scenario is that if $num is garbage you will end up calling isLarge(0).

2

solved Is the result of a print or echo a string or can they be number values in php? [closed]