問題:Array ( [0] => [1] => 3 2 [2] => 4 5 [3] => 3 4 [4] => 2 3 [5] => 1 2 )
我想檢查數組當中是否存在兩個數是相反的:比如3 2 和2 3
2 3 之間是空格隔開
自己寫了一個簡單的:
foreach($array as $value) {
$v=explode(" ",$value);
foreach($array as $num){
$m=explode(" ",$value);
if($m[0]==$v[1]&&$m[1]==$v[0]){
return "get";
}
}
}
感覺用了兩次foreach和explode,代碼冗餘,效率不高。
後來論壇發帖,有人這樣寫:
foreach($array as $value) {
$v=explode(" ",$value);
foreach($array as $num){
if(strcmp($value,strrev($num))==0){
return "get";
}
}
}
但還是兩次foreach
後來又有人回帖:
foreach($ar as $v) {
$t[] = join(' ', array_reverse(explode(' ', $v)));
}
print_r(array_intersect($ar, $t));
方法確實不錯:
$tmp = array();
foreach($arr as $item) {
$newItem = implode(' ', array_reverse(explode(' ', $item)));
if(isset($tmp[$newItem])) {
echo 'you get it!';
print_r($newItem);
}
$tmp[$item] = true;
}