PHP函数返回匹配或不匹配

时间:2011-02-22 22:55:34

标签: php boolean match

我是PHP的新手,我正在尝试编写一个带有两个变量的简单函数,如果变量相同则返回字符串“match”,如果它们不同则返回“no_match”。再次编程新手,所以提前感谢!!

2 个答案:

答案 0 :(得分:1)

您不需要执行此操作的功能:

$result = ($var1 === $var2) ? "match" : "no_match";

但如果你坚持:

function matches($var1, $var2, $strict = false) {
   return ($strict ? $var1 === $var2 : $var1 == $var2) ? "match" : "no_match"
}

用法:

$v1 = 1;
$v2 = "1";

var_dump(matches($v1, $v2)); //match
var_dump(matches($v1, $v2, true)); //no_match

$v1 = "1";

var_dump(matches($v1, $v2, true)); //match

答案 1 :(得分:0)

/**
 * Compare two values for equality/equivalence
 * @param mixed
 * @param mixed
 * @param bool compare equivalence (types) instead of just equality
 * @return string indicating a match
 */
function compare($one, $two, $strict = false) {
   if ($strict) {
      $compare = $one === $two;
   }
   else {
      $compare = $one == $two;
   }
   if ($compare) {
      return 'match';
   }
   else {
      return 'no_match';
   }
}