I'm writing code for a sortable table, where clicking the links in the header change the ORDER BY executed when generating a set of search results (the case where there there is no valid order by causes the query to not be run with order by and just return the results in the order the database returns. this is as designed). The code is being written within a framework provided by my employer.
To validate the ORDER BY part of the query I run the input through the following validation function.
<?php
function sortMode ($name)
{
$mode = '';
switch ($name)
{
case 'resnum' : $mode = 'b_resnum'; break;
case 'state' : $mode = 'st_id'; break;
case 'name' : $mode = 'lastname, firstname'; break;
case 'phone' : $mode = 'phone'; break;
case 'email' : $mode = 'email'; break;
case 'opened' : $mode = 'cs_created'; break;
default : $mode = ''; break;
}
return ($mode);
}
?>
Under testing I discovered that if no parameter was provided then the sort order would be resnum. After some experimentation, I discovered that the filtering built into the framework would cause a request for an uninitialized variable such as an unset GET parameter to return integer 0. If the above code got fed a 0 integer as its input it would always follow the first path of execution available to it.
As an experiment I tried rearranging the order of the cases in the switch statement, and found whatever was at the top would be what was executed if this function was passed a 0.
The solution to the problem was using switch (strval($name))
so the particular problem is solved, but now I'm curious as to the general behaviour of PHP switch statements. Is the behaviour I witnessed the correct behaviour for PHP? Is there some fault in PHP that's causing this, or have I made an error in my code of which I'm not aware?