-1

i am working on validation and comparisons!! i have a field that can contain the value $val=0 or $val="some-value" or $val="" or $val=0 basically i want the $val="0"or $val=0 to be validated as true..

 if($val){
    //works for $val="some-value"
//doesnot work for $val=0 or $val="0";
    } else
    {
    //works corrent for $val=""
    } 

one conditional approach i used is

$val="";

    if($val || $val==0){
    echo "true";
}
else
{
//should be false but it is true
    echo "false";
}
uneeb
  • 89
  • 1
  • 11

3 Answers3

1

did you try this?

$val = "";

if ($val == '0') {
    echo "TRUE";
        # code...
    }   
elseif ($val == "") {
        echo "FALSE";
    }   
Vincent Dapiton
  • 587
  • 1
  • 9
  • 27
  • o thanks man! i was using php functions as i got confused between string and integer comparisons that was so simple thanks...:) – uneeb Nov 29 '16 at 15:36
0

There is a useful php native function is_null

if (is_null($val) || $val === "") {
    //invalid
} else {
   //valid
}
Oleks
  • 1,633
  • 1
  • 18
  • 22
0

You can use PHP integer casting & can do it like this:

if ((int) $val === 0) {
  return true;
} else {
  return false;
}

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45