[英]Alternate line colors - understanding a code provided
在這樣的例子中 :
$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
我想了解這是如何工作的。
在這個例子中我們要做什么? 是否通過將true更改為false並將false更改為true來替換div行?
是。
$c = !$c
為其本身分配相反的$c
值。 然后在分配后評估變量。
這導致在true
和false
之間不斷變化的值。
此代碼利用了foreach
循環。 如果您有普通的for
循環,則可以改用counter變量:
for($i = 0, $l = count($posts); $i < $l; $i++) {
echo '<div'.(($i % 2)?' class="odd"':'').">{$posts[$i]}</div>";
}
如果您為變量分配了有意義的名稱,並且對空格很慷慨,那么代碼通常更容易理解:
<?php
$odd = true;
foreach($posts as $post){
echo '<div' . ( $odd ? ' class="odd"' : '' ) . ">$post</div>";
$odd = !$odd;
}
在很短的空間里發生了很多騙術。 您可以將循環的內部分為三行:
$c = !$c; // invert c
$class_part = $c ? ' class="odd"':''; // if c is true, class is odd.
echo "<div$class_part>$post</div>"; // print the <div> with or without the class
// depending on the iteration
是。
$c = true;
$not_c = !$c; // $not_c is now false
$c = !$c; // same as above, but assigning the result to $c. So $c is now false
$c = !$c; // $c is now true again
您提供的代碼段可以這樣重寫(並且可以說得更清楚):
$c = true;
foreach ($posts as $post) {
$c = !$c;
echo '<div' . ($c ? ' class="odd"' : '') . ">$post</div>";
}
$c ? ... : ...
$c ? ... : ...
語法正在使用三元運算符。 這有點像if語句的簡寫。 例如, true ? "a" : "b"
true ? "a" : "b"
計算為“ a”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.