Reputation: 105
I'm having trouble when trying to compare strings in an "if" statement.
if ($alarmonoff == "on") {
echo("checked");
}
else {
echo("unchecked");
}
In my code, even when $alarmonoff contains "on" (checked by displaying it before the statement), the displayed text is still "unchecked". Is there anything wrong? Isn't my syntax correct?
Thanks in advance!
EDIT: As I can't post code in answer comments, I'm posting this here as user689 asked. The $alarmonoff variable comes from a JSON string:
<?php
$handle = fopen("./settings.json","r");
$settings = fread($handle, 512);
$jsonsettings = json_decode($settings, true);
extract($jsonsettings);
fclose($handle);
$alarmonoff = strtolower(trim($alarmonoff));
echo $alarmonoff;
function alarmonoffcheck () {
if ($alarmonoff == "on") {
echo("checked");
}
else {
echo("unchecked");
}
}
?>
Upvotes: 0
Views: 65
Reputation: 151
Maybe try using this
$alarmonoff = strtolower(trim($alarmonoff));
This way you know that you have no blank space and a random capital won't invalidate your check.
After looking at the context of the code, $alarmonoff is out of scope, you're referencing a global variable in a local scope.
Add
global $alarmonoff;
at the top of the function alarmonoffcheck() to reference the global variable that was defined earlier.
Upvotes: 1