I am looking to create alternating designs for the content of each post returned in my loop. In short I want the first post to display left align, next right align, and so on. I have not been able to find a way to do this. Any ideas?
Try something like this:
$count = 0;
foreach ($posts as $post) {
echo "<div class=\"" . (++$count % 2 ? 'left' : 'right') . "\">"
. $post['postText'] // or whatever the crazy wordpress thing is
. "</div>"
;
}
You could loop through the results and then check if an incremented counter is even or odd and display left or right depending on that.
Have a look at the modulo operator '%'
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
...
100 % 2 = 0
101 % 2 = 1
You can have a repeating pattern of as many as you like:
0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
....
C.
Related
I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
echo '<img src="',$thumbnail_image,'" />';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}
I understand how everything with the exception of this line works.
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
I know it is getting its value from this line:
$images_per_row = 3;
But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.
Any answers at all would be appreciative!
$index % $images_per_row == 0
The % means "mod", example 4 mod 2 = 0.
A % B = the remainder when we divide A by B.
In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.
Hope it helps!
% is the modulo operator. It divides the two numbers and then returns the remainder after the division.
It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.
So, if we make 5 % 2 into a fraction and reduce it:
5 1 (this is the remainder)
--- → 2 ---
2 2
So, 5 % 2 = 1.
If we take 8 % 3 we can do the same thing:
8 2 (this is the remainder)
--- → 2 ---
3 3
So, 8 % 3 = 2.
If there is no remainder, such as in 9 % 3 then you will get 0 back. See:
9 0 (this is the remainder)
--- → 3 ---
3 3
You can write some PHP to see what the values are when doing the modulo operations:
$perRow = 3;
for ($i = 0; $i < 10; $i++) {
echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "\n";
}
Output:
0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3
I want to display rows with 4 items, per row but I want to complete my rows
How can I always get : count(myarray) % 4 = 0 ?
let's say I have : count = 29 , how can I get : 3 ?
29 + 3 = 32 --> 32 % 4 = 0
$foo = 29;
$rounded_up = $foo + (4 - ($foo % 4));
29 % 4 -> 1
4 - 1 -> 3
29 + 3 -> 32
32 % 4 -> 0
This is a math question, not a programming question. But to answer it: the missing number is (4-(count % 4)) % 4. Example: count=29 , count%4=1, 4-1=3. The extra %4 is to catch edge cases like 28: 28%4=0; 4-0=4; 4%4=0.
How about
4 - count(myarray) % 4
x - count(myarray) % x
It will give you the rest.
And as pointed out by the comment below, if you want to avoid having 4 as the result of a complete row, use this :
(4 - count(myarray) % 4) % 4
(x - count(myarray) % x) % x
Try with:
$count = count($array);
$modulo = 4;
$result = $modulo - $count % $modulo;
I'm try to dynamically generate an HTML table containing data from a database. The output looks perfect, but upon closer inspection I realized it was omitting every fourth result. I know it has something to do with the structure of my while loop and the if/else statement within, but I'm not sure what it is exactly.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<td valign='top'>";
echo "<h3>" . $person['person_name'] . " - " . $person['person_id'] . "</h3>";
echo "<label style='background-image:url(" . $person['person_pic'] . ");'><input type='checkbox' name='person[]' value='" . $person['person_id'] . "''></label>";
echo "</td>";
$i++;
}
else{
echo "</tr>";
echo "<tr>";
$i=0;
}
}
It's gotta be something simple/obvious, but it's not registering with me. Thanks!
The loop is not hitting the fourth result because of the loop limiting logic.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<p>item: $i</p>";
$i++;
}
}
Iteration 1: $i = 0
Iteration 2: $i = 1
Iteration 3: $i = 2
Iteration 4: $i = 3
Iteration 4 is never hit because it checks and sees that $i must be less than or equal to 2. If you change this to be less than or equal to 3 it will work as you want.
if ($i <= 3)
Evidently... you only increment the variable $i when the condition is met:
$i=0;
while ($person = $pull_person->fetch())
{
if ($i <= 2)
{
//output
$i++;
}
else
{
//no output
$i=0;
}
}
So this happens:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 0 no //condition not met
5 0 1 yes //loops...
...
What you observe here is that the code will skip the output of the iteration given by the number in the conditional plust 2. So, for example, if you use the condtion $i <= 3, the results are:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 4 yes
5 4 0 no //condition not met
6 0 1 yes //loops...
...
If you want to insert something each n iterations, do as follows:
$n = 3; //number of items per row
$i = 0;
while ($person = $pull_person->fetch())
{
//output item
$i++;
if ($i == $n)
{
//something each $n iterations
$i=0;
}
}
The effect is the following (assuming $n = 3):
iteration old $i new $i new row
1 0 1 no
2 1 2 no
3 2 0 yes //condition is met, $i reset to 0
4 0 1 no
5 1 2 no
6 2 0 yes //condition is met, $i reset to 0
...
Note 1: every iteration outputs an item.
Note 2: you can adjust the initial value of i to have an offset.
Misread question but will leave the answer as it may provide use anyway.
Best way is to look at the array as a 'module' (mathematically) -- i.e. use Modular Arithmetic:
if ((i % 4) == 0)
That is to say, indices 0, 4, 8, 12, 16, ... will be targeted, only. And, actually, this is how most setInterval functions work under the hood.
On a form, I used PHP to display every number from 1 to the entered number. For example, if I enter 10 on the form, it displays 1 2 3 4 5 6 7 8 9 10. Now, I want it to be able to handle negative numbers by counting up to 0 (-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0) and make every even number in the results bold, e.g., 2 4 6 8 10, etc.). I've searched exhaustively for the answers without any luck. How would any of you suggest doing this? My code for the first part is displayed below. Thank you in advance.
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
echo ($counter).'<br>';
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
You can do this
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
if( $counter % 2 == 0 )
{
echo "<strong>" . $counter . "</strong><br />";
}
else
{
echo ($counter).'<br>';
}
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
Solution 1
Ok, some more information about the %. This is a modulo. It gives you back the remaining number if you divide it by the mod number. For example
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1 this because 3 / 2 = 1 and a bit,
you can't divide the last 1 completely by 2. So remain 1
4 % 2 = 0
Solution 2
Like crush said, you can use $counter & 1. What does this do?
If you look at a number bitwise. You want to AND it wit 1.
Bitwise number 2 = 0010 AND it with 0001 and your return will be 0000 (zero).
Bitwise number 3 = 0011 AND it with 0001 and your result will be 0001 (one).
If you ceep that going and only check the last bit, you can see if it is a even number. More about bitwise operations.
I have the following PHP code working 'successfully' to display URL's:
<?php
for ($i = 0; $i <= $json->domaincount; $i++) {
echo '<td class="domainList">'.$json->$i.'</td>';
}
?>
Every forth echo I want to also
echo </tr><tr>
to start a new line in the table.
Is there an easy way to know which is every forth count?
I have $i which increments from 0 up so when it gets to 3, 7, 11 etc I need to change table line.
thx
Try this:
if ( ( $i + 1 ) % 4 == 0 ) { echo '</tr><tr>'; }
This is using the modulus operator. It divides a number and returns the remainder, so 7 % 4 = 3 (because 4 fits in once, and three is left over) and 8 % 4 = 0 (because 4 fits in evenly and there are no left overs)
Look into modulo operands (% in PHP). So the check that i % 4 == 0 would give you every fourth row.
<?php
for ($i = 0; $i <= $json->domaincount;) {
echo '<td class="domainList">'.$json->$i.'</td>';
if (!(++$i & 3))
echo '</tr><tr>';
}
?>
!($i & 3) is just a quick way of writing $i % 4 === 0 without having to use modulus. You can only use that trick for modding by powers of 2.