I have a PHP time variable that is being Var dump from a html form, after which is being converted to 12 hour time in a tcpdf file "date('h:i a ', strtotime(''))". The if statement I am using to convert the time works well however when the time variable is blank I get the current time. That is not the result I want. When a time is not chosen on the form. I want the end result to be blank. Can someone help me resolve this issue? Thank you.
$da1 is the time variable that's being dump form a separate html file
if ($da1 == ""){$da1 = "";}else {$da1 = date('h:i a ', strtotime($da1));}
CodePudding user response:
First of all you should not check $da1 is fulfilled like you do now. Avoid weak comparison like this.
if($da1 == "")
How are you taking data from the form and put them into $da1 variable? To be safe you could check whether $da1 is empty. If so than you could set it to be just null. I don't get it why you set it as empty string. To be more clear you could invert the if-else. If $da1 is not empty set your time variable, else set is as null.
if (!empty($da1)) {
$da1 = date('h:i a ', strtotime($da1));
} else {
$da1 = null;
}
Also to avoid stupid mistakes you should not use the same variable you get your data from a form to work with them rightafter. Also to reduce cyclomatic complexity you could set your time variable as null by default and only set it's value if $da1 exists.
$savedTime = null;
if (!empty($da1)) {
$savedTime = date('h:i a ', strtotime($da1));
}
PS. Comparing just $da1 value will also be just fine. At all you don't even need to use empty.
if (!$da1) {...