I have a switch case statement in a PHP script that returns a string value based on the ‘Day’ and ‘Hour’ value supplied by a Ajax call from a JS file.But whenever the values are 0(i.e, Sunday for the day variable and 0 as in midnight for the hour variable) the statement doesn’t work and the value returns empty.I can’t seem to find a solution here is a shorter version of the code for the PHP function and the Ajax Call;
function getDayTimeData($day, $time){
$program = "";
switch($day){
case 0: //Sunday
switch($time){
case $time < 1:
$program = 'Be Our Guest';
break;
case $time < 6:
$program = 'Club Technoise';
break;
case $time < 12:
$program = 'Morning Juice';
break;
case $time < 21:
$program = 'Detox';
break;
case $time < 24:
$program = 'Disco Ball';
break;
}
break;
}
}
if(isset($_POST["DayData"]) && isset($_POST["TimeData"]))
{
echo(getDayTimeData($_POST["DayData"],$_POST["TimeData"]));
}
Here’s is the Jquery Ajax Script
function getDayTimeAjax(_day,_time){
var def2 = $.Deferred();
setTimeout(function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
var xhr = $.ajax({
type: 'post',
url: 'returnPoster.php',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {DayData: _day, TimeData: _time},
dataType: 'text',
success: function(x){
programInfo = x;
def2.resolve();
}
})
},2000);
return $.when(def2).done(function(){}).promise();
}
var d = new Date();
var programInfo = ".";
setInterval(function () { updateProgram() }, 3000);
function updateProgram(){
getDayTimeAjax(d.getDay(),d.getHours()).done(function(){
console.log(programInfo.trim());
})
}
EDIT: Sorry guys looks like I have given some misinformation on the subject as I was in kind of a hurry when I set this thread up.The problem only occurs when the $time value is 0.The values seem fine up until "case $time <1:" operation occurs.From there on even though the $time variable has a value of 0, It doesn’t execute the code block inside the first case, so the program variable stays empty.All other values returned the values from the switch statement.
4
Answers
Your problem lies with the switch statement, if you take this:
And fill in a value for $time, like 0:
Then compare the value in the
switch()
call to the value aftercase
:Well, this—and all other comparisons—are
false
. If you really want to use a comparison using less-than in your switch statement, you’d need to do this:Then the comparison would be:
Note that in your original code, when the value for
$time
is not 0, it’d compare for example3 == true
which, becauseswitch
does not check strictly (it uses ==, not ===), istrue
. It would always return the first result ‘Be our guest’, no matter the value.I think you can try this, it may work with the first switch also, but i prefer to use if instead:
You cannot compare integer value and time like this,
try to compare same type values.
Here is a small example. This will echo a program based on time. To identify day I recommend to use IF instead of switch case.