我确信这是一个简单的解决方案 - 我写了发现这个函数结束了,并且认为我会尝试使用array_walk函数而不是单独测试每个字符串。我假设array_walk函数的结果是false但它返回1 ...如何测试所有字符串并返回false如果它没有找到匹配?感谢
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);
}
}
答案 0 :(得分: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);
答案 1 :(得分: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; }
}
}
}
}
答案 2 :(得分:1)
array_walk()
只是迭代数组的元素并返回true
,如果它能够做到的话。 (echo
将boolea true
投放到字符串'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()
且无用。
答案 3 :(得分:0)
如果要将函数应用于所有值并返回单个结果,则应使用array_reduce
。
答案 4 :(得分: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 :(';
}
}
}