Lee Jeffries Lee Jeffries - 5 months ago 9
PHP Question

See if _REQUEST value is 0 or 1 or anything else

I am trying to see if a _REQUEST['abc'] value is either 1 or 0, or else set it to "na"

If I use intval(), then var=abc intval($abc) = 0, as does a blank value "?abc="

How can I tell if abc=0 or abc=1, else abc = na?

I've tried

if( intval( $inputs[ 'abc' ] ) !== 0 && intval( $inputs[ 'abc' ] ) !== 1 )
{
$inputs[ 'abc' ] = 'na';
}


EDIT:

For transparency, my final solution was:

if( strval( $inputs['abc'] ) !== '0' && strval( $inputs['abc'] ) !== '1' )
{
$inputs['abc'] = 'na';
}


So maybe my solution was a product of two, but thanks to all who helped me

Answer

Assuming by _REQUEST you meant $_REQUEST, then we might want to approach it like so:

    <?php
        // ASSIGN THE VALUE OF THE $_REQUEST GLOBAL TO $inputs
        $inputs     = $_REQUEST;

        // YOU MAY NOT NEED TO CAST TO INTEGER TYPE DURING THE CHECKS
        // ESPECIALLY SINCE 0 IS INVOLVED... THE BEST BET IS EVEN TO CAST ALL TO STRING...
        // SO WE FIRST CHECK THAT $inputs['abc'] IS NOT EQUAL TO THE STRING VALUE "0"
        if( ($inputs['abc'] . "") !== "0" ){
            // THEN AGAIN; WE CHECK THAT THE STRING VALUE OF $inputs['abc'] IS NOT "1"
            if( ($inputs['abc'] . "" ) !== "1" ) {
                // IF OUR CONDITION IS SATISFIED, WE GO AHEAD AND DO THE ASSIGNMENT: $inputs['abc'] = 'na' 
                $inputs['abc'] = 'na';
            }
        }
    ?>
Comments