Irregularities with posted checkbox data

Discussion in 'PHP' started by Weirfire, Mar 29, 2007.

  1. #1
    After finishing a script for one of my clients I noticed an irregularity with the way PHP processes posted data using checkbox fields.

    if you do the following check;

    if(!$_POST['checkbox1']=='On'){
    return true;
    }
    PHP:
    it will return false whether or not the value is 'on' or 'On'

    if you do the following check;

    if($_POST['checkbox2']=='on'){
    return true;
    }
    PHP:
    it will only return true if you use lower case 'on'


    Anyone else noticed this before?
     
    Weirfire, Mar 29, 2007 IP
  2. Wyla

    Wyla Well-Known Member

    Messages:
    924
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    140
    #2
    php is case sensative
     
    Wyla, Mar 29, 2007 IP
  3. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #3
    if it really matters to your code, you could always strtolower() the posted variable
     
    krakjoe, Mar 29, 2007 IP
  4. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #4
    About "strange" behaviour of the first example. ! (not) operator has higher priority than == (comparison) operator, so the PHP interpreter firstly calculates !$_POST['checkbox1'] and after that it compares resulting value with 'On'. To avoid this "strange" behaviour use parentheses. So your code could be rewritten as:
    if(!($_POST['checkbox1']=='On'))
    {
     return true;
    }
    PHP:
    For more information see Operator Precedence
     
    wmtips, Mar 29, 2007 IP
  5. Weirfire

    Weirfire Language Translation Company

    Messages:
    6,979
    Likes Received:
    365
    Best Answers:
    0
    Trophy Points:
    280
    #5
    I understand operator precedence but I just thought it was unusual that it would accept "On" as "on" when comparing for the negated version. The operator precedence has no correlation to the values I'm passing into the conditions.

    Of course the default value for checkboxes is always lower case "on" so I was in error to insert them as "On" in the first place.

    Just thought it was strange that it would give me 2 different results.
     
    Weirfire, Mar 30, 2007 IP