Compare strings in PHP excluding Null or empty values -
i have simple question comparing strings in php.
i want know if 2 strings (also applicable in other type) equal, want exclude null or empty values of comparison, so, i'm doing this:
if (!empty($var) && $var == $vartocompare) { //do stuff } it's working fine, i'd know if there exists operator or function avoiding empty() part.
my background: i'd know in generic way, here background clarify. have 2 or more variables , need compare them variables in database, if have null in database , var null (or empty string) expect false. using === operator if 2 strings null or "" receive true. see example:
$myvars = $this->getarrayofvars(); $var1 = $mydb->getvar1();// null or "" $var2 = $mydb->getvar2();// null or "" if ((!empty($var1) && $var1 == $myvars[1]) || (!empty($var2) && $var2 == $myvars[2])) { //do stuff // enter here when strings equal, avoiding null or empty values } i checked docs, didn't find anything. knows function can this?
the best practice make own function :
/** return false if parameter empty() or $var1 !== $var2 **/ function strictlyequalandnotnull($var1, $var2) { return (!empty($var1) && $var1 === $var2); } which gives :
$myvars = $this->getarrayofvars(); $var1 = $mydb->getvar1();// null or "" $var2 = $mydb->getvar2();// null or "" if (strictlyequalandnotnull($var1, $myvars[1]) || strictlyequalandnotnull($var2, $myvars[2])) { // stuff // enter here when strings equal, avoiding null or empty values }
Comments
Post a Comment