Adding class to a foreach loop every N times - php

I have an users list, each user is wrapped by a div, this way
<div class="users">
<div>user 1 content</div>
<div>user 2 content</div>
<div>user 3 content</div>
<div>user 4 content</div>...
</div>
then all are displayed this way:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
...... and so on
divs numbers 1,4,7,10.. should have a class called class_left for instance,
divs numbers 2,5,8,11,14.. should have a class called class_center and
divs numbers 3,6,9,12,15... should have a class called class_right
I am not quite sure how to do it.
Thank you.

You can simply do this by using modulus operator with 3.
Here is a pseudo code:
if(div_number % 3 ==1)
class = class_left;
else if(div_number % 3 == 2)
class = class_center;
else
class=class_right;

I don't know how you're using your code, but you can use modulus operator in this way: if column number modulus 3 is 1 then you're on the left, else if the result is 2 you're on the center, else with result equal 0, you're on the right.

Suppose that $data is your array of data:
<?php $aligns = array('right', 'left', 'center'); ?>
<div class="users">
<?php foreach($data as $key => $value): ?>
<div class="class_<?php echo $aligns[$key % 3]; ?>">
<?php var_dump($value); ?> // User X's Content
</div>
<?php endforeach; ?>
</div>

Maybe try this way:
var curr = 0;
users.forEach(user){
curr++;
switch(curr){
case 1:
user.class = 'class_left';
case 2:
user.class = 'class_center';
case 3:
user.class = 'class_right';
curr = 0;
}
}
This is only javascript example. Please use your language.

Try this:
$i = 1;
$last = 100;
for ($i =1; $i<$last; $i=+3) {
echo "<div class='class_left'>user ".$i." content</div>";
echo "<div class='class_center'>user ".($i+1)." content</div>";
echo "<div class='class_right'>user ".($i+2)." content</div>";
}
Or if you want a function that will take the number and return the class name you should try something like:
function getClass($num) {
if (!$num % 3) {
return 'class_right';
}
if (!($num + 1) % 3) {
return 'class_center';
}
if (!($num + 2) % 3) {
return 'class_left'
}
}

This code works for any number of div elements per row. (If you set $divsPerRow to 2, class_center will not be used. If you set it to 1, neither will class_right.)
$divsPerRow = 3;
$users = range(1, $divsPerRow * 3);
echo '<div class="users">' . PHP_EOL;
for ($i = 0; $i < count($users); $i++) {
$class = "left";
$column = $i % $divsPerRow + 1;
if ($column > 1) {
$class = ($column == $divsPerRow) ? "right" : "center";
}
echo '<div class="class_' . $class . '">user ' . $users[$i]
. ' content</div>' . PHP_EOL;
}
echo '</div>' . PHP_EOL;

What is you looking for is:
(i-1)%3 == 0

Related

How to set 2 different classes by if else condtion in foreach loop with predefined order?

Suppose I have 10 records, and 2 different classes namely c1, c2
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
i want the if else condition where class order needs to maintained like c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
foreach(x as y){
if() {
<div class="<?php echo $class1;?>">..content..</div>
} else {
<div class="<?php echo $class2;?>">..content..</div>
}
class order should be c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
Check the page url http://themesflat.com/html/nah/portfolio-creative.html
You can use a bitwise operator (&) here, and with 2 and this will toggle the class...
$i = 0;
foreach($x as $y){
if($i & 2) {
$class = "1";
} else {
$class = "2";
}
echo "<div class=$class>..content..</div>";
$i++;
}
I've extracted the echo out as this keeps it consistent, just have a variable for the class you want to have and put that in the if instead.
You can do it with a separate counter
$current = 'c2';
$count = 1;
for ($i = 0; $i < 10; $i++) {
echo '<div class="'. $current . '">..content..</div>';
if ($count == 2) {
$current = $current == 'c1' ? 'c2' : 'c1';
$count = 0;
}
$count++;
}
Demo: https://3v4l.org/7ftjg
This will of course work just as well in a foreach-loop.
Note: If it's only about styling the divs differently, you could do this in CSS alone. Here's a similar question and answer: nth-child: how to pick elements in groups of two
I'm pretty sure you can resolve the problem via css pseudo class :nth-of-type but if you prefered PHP you can try the following example.
<?php
$class_types = ['c2', 'c1'];
$records = array_fill(0, 10, '..content..'); // replace with your records
$records_length = count($records);
$html_output = '';
foreach ($records as $index => $item) {
$type = floor($index / $records_length * $records_length / 2) % 2;
$class = $class_types[$type];
$html_output .= sprintf('<div class="%s">%s</div>', $class, $item);
}
echo $html_output;
Try this code:
$counter = 1;
for($i=0;$i<=10; $i++){
if($counter==1 or $counter==2) {
echo '<div class="c1">..content..</div>';
} else {
echo '<div class="c2">..content..</div>';
}
if($counter==4){
$counter=0;
}
$counter++;
}
?>
How about we chunk the main array into an array or arrays of two
like
<?php
$chunked_array = array_chunk( $your_array , 2 );
// This will give us an array of 2 elements array
// now we will loop
for( $i = 1 ; $i < count( $chunked_array ); $++ ){
$contents = $chunked_array[$i];
foreach( $contents as $content ){
if ( $i%2 == 0 ){
//<div class="<?php echo $class1;?>">..content..</div>
}else{
//<div class="<?php echo $class2;?>">..content..</div>
}
}
}
using this way we have one loop and it will always be in a group of two even when your data grow or shrink

How to break foreach loop or for loop into 10 records

Suppose I have 56 records in my database. I'm using a FOR LOOP to display them.
I want to append div after 10 records every time.
<?php
$a = 56;
for($i=0;$i<$a;$i++){
echo "<div>";
echo $i."</br>";
echo "</div>";
}
?>
output:
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
...
<div>56</div>
I want to append <div> after 10 records each time
<div>
0
1
2
.
9
</div>
<div>
10
11
.
19
</div>
.
.
<div>
51
52
.
.
56
</div>
You can use the modulus operator for that.
<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
echo $i . "<br />";
if (($i+1) % 10 == 0) {
echo "</div><div>";
}
}
echo "</div>";
?>
Note that if the number of loops is unknown - it's possible that $a will be 9, and your output will be:
<div>
0
...
9
</div><div>
</div>
If you want to prevent the duplicate of the close-open div in case of exact division, you can change your code to:
<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
echo $i . "<br />";
if (($i+1) != $a && ($i+1) % 10 == 0) {
echo "</div><div>";
}
}
echo "</div>";
?>
You need to append the opening and the closing divs based on some condition which primarily are
If it is the first iteration
If it is the tenth iteration
If it is the last iteration
Here is a sample code:
$a = 56;
for ($i = 0; $i < $a; $i++) {
// If it is the first iteration, echo a opening div
if ($i == 0)
echo "<div>";
// If it is a tenth iteration but not the last one then append a closing and a opening div
if ($i != 0 && $i % 10 == 0 && $i != $a - 1)
echo "</div><div>";
echo $i.
"<br>";
// If it is the last iteration, append a closing div
if ($i == $a - 1)
echo "</div>";
}

Split query results in 2 div's

i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}

Adding a style to every 2nd result for 2 rows, then skipping 2 results?

This is a bit tricky to word but;
What I'm trying to do is add the style 'background-color: black;' to only some results in my query.
So, if i was to echo my results it would display like this;
1st result no style
2nd result black
3rd result black
4th result no style
5th result no style
7th result black
8th result black
9th result no style
10th result no style
My query
$getusers= $db->query("SELECT * FROM users");
while($users= $getusers->fetch_assoc()) {
$color = ??????????????? not sure
echo '<div style="background-color: ' . $color . ';">';
echo $users['username'];
echo '</div>';
}
Use a placeholder variable.
Follow the progression of $i in my example below.
$getusers= $db->query("SELECT * FROM users");
// Starting at 2 will cause "no style" to happen only once on first pass.
$i = 2;
while($users= $getusers->fetch_assoc()) {
// if $i is 3 or 4 value would be "black"
$rowBg = "background-color:black";
// Set to an empty string (no style) if $i is 1 or 2.
if($i <= 2) {
$rowBg = "";
}
$i++;
// Start over!
if($i > 4)
$i = 1;
echo '<div style="' . $rowBg . ';">';
echo $users['username'];
echo '</div>';
}
How about this:
$getusers= $db->query("SELECT * FROM users");
$r = 1;
while($users= $getusers->fetch_assoc()) {
$style = ($r == 2 || $r == 3) ? 'style="background-color: black"' : ''; // black for every 2nd & 3rd row
$r = ($r == 4) ? 1 : $r+1; // reset count to 1 when we get to 4
echo '<div $style>';
echo $users['username'];
echo '</div>';
}
$count = 1;
$getusers= $db->query("SELECT * FROM users");
while($users= $getusers->fetch_assoc()) {
$color = "#000000";
if($count == 2 || $count == 3){
echo '<div style="background-color: ' . $color . ';">';
if($count==3){
$count=0;
}
}
else{
echo "<div>";
}
echo $users['username'];
echo '</div>';
$count++;
}

If value is greater/lesser than xyz

I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.

Categories