It's because of the way php casts strings to ints. When you pass in a 0
, you are asking it to do an integer comparison, so it will convert all of your case keys to integers. When php casts a string
to an int
, it looks for an actual number at the beginning of the string, and gobbles the number up until it hits a non-number. Since the string "resnum" has no numbers, it returns 0. See here:
php > echo (int)"100";
100
php > echo (int)"300 dogs";
300
php > echo (int)"resnum";
0
php > echo (int)"resnum 100";
0
Since all of those strings cast to 0, the first case would evaluate to true
since 0 == 0
.
Resources:
String conversion to numbers
Type comparison tables
Nitpick time. When you're doing simple case statements that map a string to a string, use an array. It's much clearer and actually faster:
function sortMode ($name)
{
$modeMap = array(
'resnum' => 'b_resnum',
'state' => 'st_id',
'name' => 'lastname, firstname',
'phone' => 'phone',
'email' => 'email',
'opened' => 'cs_created'
);
return isset($modeMap[$name]) ? $modeMap[$name] : '';
}
If the $name
is set in the map, we return the value that key is mapped to. Otherwise, we return an empty string, which takes the place of the default
case.
As a bonus, you would have noticed the bug earlier if you did the above method, because it would be trying to access $modeMap[0]
and would have returned your default case instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…