0

我确信这是一个简单的解决方案 - 我写了这个函数,并认为我会尝试使用 array_walk 函数而不是单独测试每个字符串。我假设 array_walk 函数的结果是假的,但它返回 1...如果它没有找到匹配项,我如何让它测试所有字符串并返回假?谢谢

class {    
    function endsWith($value,$key,$haystack)
    {
        $length = strlen($value);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $value);    
    }

    function thing()
    {
        $email = "should@returnfalse.info";
        $arr = array("@test.net","@test.org.uk","@test.co.uk","@test.com");

        echo array_walk($arr,array($this,"endsWith"),$email);
    }
}
4

5 回答 5

2

的返回值array_walk不是由回调函数决定的;它只会通知您遍历整个阵列是否成功完成。

您可能想研究一些替代方案。

这将返回匹配元素的数量,也将用作布尔测试,但无论如何它都会评估每个元素:

echo count(array_filter($arr,array($this,"endsWith")));

endsWith一旦检测到匹配,这将停止评估元素,true如果有匹配将返回,false否则:

$self = $this;
// cast to int because false is printed as the empty string
echo (int)array_reduce($arr, 
                       function($result, $v) use ($email, $self) {
                          return $result || $self->endsWith($v, null, $email);
                       }, 
                       false);
于 2012-10-18T09:35:50.463 回答
1

array_walk()只需遍历数组的元素并返回true,如果它能够做到的话。(echo将 booleatrue转换为字符串'1')看看array_recude()

$that = $this; // Cannot access $this directly before PHP 5.4
var_dump(
  array_reduce (
    $arr, 
    function($result, item) use ($email, $that) { return $result || $that->endsWith($item, null /* not used anyway */, $email);}, 
    false
  )
);

附加$key在 中未使用且无用endsWith()

于 2012-10-18T09:28:20.920 回答
1

尝试这个

class {    
    function thing()
    {
        $email = "should@returnfalse.info";
        $arr   = array("@test.net","@test.org.uk","@test.co.uk","@test.com");

        foreach ($arr as $domain) {
            $length = strlen($value);
            if ($length != 0) {
               if (substr($email, -$length) === $domain) { echo $domain; break; }
            }
        }
    }
}
于 2012-10-18T09:28:04.997 回答
0

自 PHP 5.3 起,您可以使用匿名函数:

class {
    function thing()
    {
        $email = "should@returnfalse.info";
        $arr = array("@test.net","@test.org.uk","@test.co.uk","@test.com");
        $match = '';
        $found = false;
        array_walk($arr,function($value) use (&$match, &$found, $email) {
            $length = strlen($value);
            if ($length == 0) {
                $found = true;
                return;
            }

        if (substr($email, -$length) === $value) {
            $match = $value;
            $found = true;
        }
        });
        if ($found) {
            echo 'Found match: ' . $match;
        } else {
            echo 'No match found :(';
        }
    }
}
于 2012-10-18T09:38:58.640 回答
0

如果要将函数应用于所有值并返回单个结果,则应使用array_reduce.

于 2012-10-18T09:28:31.977 回答