0

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");
        }
    }
?>
7
  • 2
    check the spaces and the invisible characters such as chr(13), chr(10) ... Commented Jan 15, 2014 at 18:02
  • 4
    Doubtful. There's nothing wrong with the code you show. Do a var_dump($alarmonoff) Commented Jan 15, 2014 at 18:02
  • I'd be more inclined to think that $alarmonoff isn't being set properly. Commented Jan 15, 2014 at 18:03
  • Try to echo($alarmonoff) and provide the result! Commented Jan 15, 2014 at 18:14
  • echo $alarmonoff gives "on", without quotes of course. I don't think there are any invisible characters (if you meant spaces Sebas), because when I try to highlight the echoed value, I can only select the two letters "o" and "n"... Commented Jan 15, 2014 at 18:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Could you post some more code for context, maybe some snippet of where it was set? Also make sure it was in the same scope as this block.
Sure, check my original question for the code, I've edited it!
The variable is out of scope, you either need to call it by reference or change the header of the function to include a variable so you can pass it to the function.
Or add this line in your function before you check the string: global $alarmonoff; that will use the global version of this variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.