簡體   English   中英

如何檢查foreach循環內的值是否相同

[英]How to check values inside foreach loop are same or not

我有一個 foreach 循環

foreach ($age as $ages) {
   echo $ages;
}

運行此代碼時,結果是

3
3

或者

1
3

我想檢查值是否相同。 例如

if (values are same) {
  do something...
}
else {
  do something...
}

我真的找不到如何檢查值是否相同。

如果您要檢查所有值是否相同,只需使用array_unique()刪除重復值。 然后檢查剩余數組的大小是否等於1:

$is_all_duplicates = count(array_unique($array)) === 1;

如果有任何重復將觸發此條件,只需使用array_unique()刪除重復值,然后比較兩個 arrays 的大小。 如果它們不相同,則您有重復的值:

$is_some_duplicates = count(array_unique($array)) < count($array);

如果值相同,則array_count_values將只有一個元素:

$a = [1,2,3,3];
$acv = array_count_values($a);
if (count($acv) == 1) {
    echo 'values are the same';
} else {
    echo 'values are NOT the same';
}


$a = [3,3,3];
$acv = array_count_values($a);
if (count($acv) == 1) {
    echo 'values are the same';
} else {
    echo 'values are NOT the same';
}

小提琴

但最優化的解決方案是一個簡單的循環,第一個值不等於break的第一個值:

$a = [1,2,3,3];
$hasSameValues = true;

$firstElem = array_slice($a, 0, 1)[0];
foreach ($a as $el) {
    if ($el != $firstElem) {
        $hasSameValues = false;
        break;
    }
}

if ($hasSameValues) {
    echo 'values are the same';
} else {
    echo 'values are NOT the same';
}

echo PHP_EOL;

$a = [3,3,3];
$hasSameValues = true;

$firstElem = array_slice($a, 0, 1)[0];
foreach ($a as $el) {
    if ($el != $firstElem) {
        $hasSameValues = false;
        break;
    }
}

if ($hasSameValues) {
    echo 'values are the same';
} else {
    echo 'values are NOT the same';
}

又一個小提琴

你可能想“說”:)

foreach ($ages as $age) {
   echo $age;
}

我了解您想檢查是否只有最后一個值與實際值相等。
要檢查,寫這個:

$ages = [1,1,7,2,2,4,1,2];

foreach ($ages as $age) {
    if(isset($temp) ? !($temp == $age)  : true){
       echo $age;
    }
    $temp = $age;
}

結果是:172412
編碼:
檢查是否設置了變量$tempisset($temp)
如果已設置,請檢查它是否與最后一個年齡值不相等: !($temp == $age)
如果$temp未設置,則設置true以從 if 語句運行代碼(回顯年齡)(首次運行時是否存在)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM