簡體   English   中英

在執行循環之前了解for-each循環的計數

[英]Know the count of for-each loop before executing that loop

我怎么可能知道-在php中執行循環之前,foreach循環將運行多少次。
換句話說,我想知道該特定循環的計數。
我想根據計數應用一些不同的CSS。

使用函數count獲取數組中的數字量。

例:

$array = array('test1', 'test2');
echo count($array); // Echos '2'

或者,如果您想成為分類工程師,則可以這樣設置:

$array = array('test1', 'test2');
$count = 0;
foreach ($array as $a) { $count++; }

這樣就可以為您計數了, $count變量將保留計數,希望這對您有所幫助。

只需對數組進行count()並將輸出用作條件,例如:

if (count($array) > 100) {
    // This is an array with more than 100 items, go for plan A
    $class = 'large';
} else {
    // This is an array with less than 100 items, go for plan B
    $class = 'small';
}

foreach ($array as $key => $value) {
    echo sprintf('<div id="%s" class="%s">%s</div>', $key, $class, $value);
}

暫無
暫無

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

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