I’m trying to test the === operator (which tests for equality of value and type)
I’m also trying to use the ? (ternary) operator to display appropriate results.
I want to display “Is $var1 the same as $var2 ? Yes” but all It displays is ‘Yes’
Here is the code… what am I doing wrong?
$var1 = 14;
$var2 = '14';
$result = ($var1 == $var2);
echo '<p>Is $var1 the same as $var2 ?' . $result ? 'Yes' : 'No' . '</P>';
$result = ($var1 === $var2);
echo '<p>Is $var1 the same as $var2 and of the same type?' . $result ? 'Yes' : 'No' . '</P>';
edit: The reason I’m using single quotes instead of double quotes is so that it displays ‘$var1’ and ‘$var2’ instead of displaying what’s IN those variables (which is what would happen if I used double quotes)
Is there a better way of doing that? (displaying the name of a variable instead of its contents when using double quotes)
Just making a guess, but it’s decently likely that what is happening is that when you do your first $var1 == $var2, the internal type of $var2 is changed to being an int, which then makes your test for type equality come out true.
The ternary operator evaluates the result of the expression before the ‘?’ and returns the expression before ‘:’ if true and the expression after ‘:’ if false. This expression:
‘<p>Is $var1 the same as $var2 ?’ . $result
is always true since it is a non-empty string, regardless of the value of $result. Hence the ternary operation
‘<p>Is $var1 the same as $var2 ?’ . $result ? ‘Yes’ : ‘No’