In an example like this:
$c = true; // Let's not forget to initializ开发者_JAVA技巧e our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
I would like to understand how this works.
What are we trying to do with this example? Do an alternate div row by changing true to false and false to true?
Yes.
$c = !$c
assigns the opposite value of $c
to itself. The variable is then evaluated after the assignment.
This results in a constantly changing value between true
and false
.
This codes takes advantage of the foreach
loop. If you have a normal for
loop, you could use the counter variable instead:
for($i = 0, $l = count($posts); $i < $l; $i++) {
echo '<div'.(($i % 2)?' class="odd"':'').">{$posts[$i]}</div>";
}
If you assign meaningful names to your variables and you're generous with white-space, the code is normally easier to understand:
<?php
$odd = true;
foreach($posts as $post){
echo '<div' . ( $odd ? ' class="odd"' : '' ) . ">$post</div>";
$odd = !$odd;
}
There is a bunch of trickery going on in a very short space here. You could split the inside of the loop up into three lines:
$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
Yes.
$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
The snippet you provided could be rewritten (and arguably made more clear) like so:
$c = true;
foreach ($posts as $post) {
$c = !$c;
echo '<div' . ($c ? ' class="odd"' : '') . ">$post</div>";
}
The $c ? ... : ...
syntax is using the ternary operator. It's kind of like a short-hand if statement. For example, true ? "a" : "b"
evaluates to "a".
Assignments in PHP return the newly assigned value. So $c = !$c
returns true
when $c
was false
; false
when $c
was true
.
The ternary operator ( ? : ) evaluates the part before ':' when the condition before '?' is true, otherwise the part after the ':'. So it outputs the text either before or after the ':'.
As others stated, it's probably better to write this in a more understandable way.
精彩评论