2012-10-18 45 views
0

我敢肯定,這是一個簡單的解決方案 - 我 發現這個功能的endsWith我想我會嘗試array_walk函數,而不是單獨測試每個字符串。我假設array_walk函數的結果是假的,但它返回1 ...我如何得到它來測試所有的字符串,並返回假如沒有找到匹配?由於PHP測試array_walk導致

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

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

    function thing() 
    { 
     $email = "[email protected]"; 
     $arr = array("@test.net","@test.org.uk","@test.co.uk","@test.com"); 

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

如果array_walk傳遞所有元素,您將始終爲true;假 - 如果array_walk無法做到 – Sergey

+0

試試這個:var_dump($ arr); array_walk($改編,數組($此, 「的endsWith」),$電子郵件);後續代碼var_dump($ ARR); – Sergey

回答

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); 
+0

的array_reduce液返回0,即使存在匹配(PHP 5.3),但我要看看我是否能得到它的工作,它看起來很整齊。謝謝 –

+0

@JimSMith:我在這裏誤解了你的意圖。更新的答案應該按原樣工作。 – Jon

1

試試這個

class {  
    function thing() 
    { 
     $email = "[email protected]"; 
     $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; } 
      } 
     } 
    } 
} 
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()

+0

感謝,這個返回意外「)」的錯誤不知道是什麼問題,但 –

0

如果您想將函數應用於所有值並返回單個結果,則應使用array_reduce

0

由於PHP 5.3,你可以使用匿名函數:

class { 
    function thing() 
    { 
     $email = "[email protected]"; 
     $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 :('; 
     } 
    } 
}