I am way confused with a comparison “error”. The way I coded this comparison, I want to make sure that if the user inputs any value other than 0 or 1 (Or no value), the result should be 0:
session_start();
function test( $status = 0 ) {
if( !isset($_SESSION['status']) ) { $_SESSION['status'] = 0; }
else {
switch( $status ) {
case 0: $_SESSION['status'] = $status;
break;
case 1: $_SESSION['status'] = $status;
break;
default:
$_SESSION['status'] = 0;
$status = 0;
}
}
echo 'Variable value: ' . $status;
echo ' | Session value: ' . $_SESSION['status'] . "<br/>";
}
test();
test(0);
test(1);
test(999);
test('ready');
HOWEVER, it breaks at test('ready'); BECAUSE it outputs Variable value: ready | Session value: ready RATHER THAN Variable value: 0 | Session value: 0. It should continue to work well (and go for case o:) even if it is comparing numbers against a string.
BTW: The result is the same even if I replace switch for if( $status ===
=== EDIT: 12/19/2012 ===
Thanks to @bryan-b and @jatochnietdan comments and answers: -Because a string (when compaired with numbers [if( 0 == ‘string’)] ) is compared as 0
That helped me figure out the problem and learned that, unlike in other languages, rather than automatically returning false in a comparison, since they are of different data-types; php compares string variables as if their value is 0 when compared against numbers.THAT’S SOMETHING TO WATCH OUT FOR.
This is the corrected (working) code:
session_start();
function test( $status = 0 ) {
if( !isset($_SESSION['status']) ) { $_SESSION['status'] = 0; }
else {
switch( $status ) {
case 1: $_SESSION['status'] = $status;
break;
default:
$_SESSION['status'] = 0;
$status = 0;
}
}
echo 'Variable value: ' . $status;
echo ' | Session value: ' . $_SESSION['status'] . "<br/>";
}
test();
test(0);
test(1);
test(999);
test('ready');
Thank you @bryan-b and @jatochnietdan!!!
PS. I wish I could vote 2 answers.
I think the problem here is that php is casting the string “ready” to an integer, so the case comparison works. From the php docs (http://php.net/manual/en/function.intval.php):
I’ve added an echo into the (working) function showing what php is doing when casting the string to an int for the switch comparisons. You need to be checking the exact value and type of the passed in status.