PHP LI count divisions - php

I have a loop that displays <li>'s and I need to add a class to the 1st and then every six <li>'s
Example:
while ($db_field = mysql_fetch_assoc($result)) {
<li (if mod of 6 add class="something")>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li class="something">Six</li>
<li>Seven</li>
}
...

It's quite easy using the modulus % operator:
$counter = 0;
while ($r = mysql_fetch_assoc($res) {
$isSixthsLi = (bool) (($counter++) % 6 == 0);
echo $isSixthsLi ? '<li class="something">' : '<li>';
echo htmlentities($r['content']);
echo '</li>';
}
The ($counter++) % 6 expression means the remainder of $counter divided by 6, then increment $counter. If the remainder is zero (and this is true for 0, 6, 12, ...), then you print the <li> with a class name, else you did not.

i think this list is coming dynamically then you can use
<?php
$i=0;
foreach ($in as $v){
$i++;
$class = (!$i%6) ? "something : ""; ?>
<li class="<?=$class?>"><?=$v?></li>
<?php } ?>
Note : i have use shorthand tag <?= , you can use <?php echo instead

Related

PHP - Assign some class to li tag based on some condition inside loop

I have following Two-dimensional array:
$data = array
(
array("1.2"),
array("2.5"),
array("4.7"),
array("5.7"),
array("3.5"),
array("7.2"),
array("4.7"),
array("3.5")
);
Now I am displaying my records through loop:
<ul>
<?php
for($i=0; $i<count($data); $i++):
?>
<li><?php echo $data[$i][0]; ?></li>
<?php
endfor;
?>
</ul>
and this is the result:
Now I want to check some condition inside loop and add class="red" to li.
Example 1:
If 4.7 found inside the loop, add class="red" to next all li tags.
Example 2:
If 3.5 found inside the loop, add class="red" to next all li tags.
Example 3:
If 5.7 found inside the loop, add class="red" to next all li tags.
Any idea how to add class to li tags when some condition match.
Thanks.
You can just switch on the class as soon as a matching item is found.
$switch_value = '4.7'; // set the value where you want to switch colors
$class = ''; // initialize the class to empty string
foreach ($data as $value) {
echo "<li$class>$value[0]</li>";
// set the class to red the first time the value is found
if ($value[0] == $switch_value) $class = ' class="red"';
}
It's important to set the class after echoing the list item to get the output you want.
You can do it this way:
<ul>
<?php
$class = ''; $num = 4.7;
for($i=0; $i<count($data); $i++):
?>
<li class='<?php echo $class; ?>'><?php echo $data[$i][0]; ?></li>
<?php
if( $data[$i][0] == $num ) $class = 'red';
endfor;
?>
</ul>
Just change the $num to desired value programmatically.
Edit: move the if block to end of for block to leave the number's occurrence.
Just check a condition with a value, and assign it
<ul>
<?php
$isRed = false;
$value_to_search = 3.5;
for($i=0; $i<count($data); $i++):
?>
<li class="<?php echo ($isRed == true)?'redClass':'';"><?php echo $data[$i][0]; ?></li>
<?php
if($data[$i][0] == $value_to_search )
$isRed = true;
endfor;
?>
</ul>
I guess you can use something like:
<ul>
<?php
$red = false;
for($i=0; $i<count($data); $i++){
if($data[$i][0] == "3.5" or $data[$i][0] == "4.7" or $data[$i][0] == "5.7" or $red){
echo "<li class=\"red\">{$data[$i][0]}</li>";
$red = true;
}else{
echo "<li>{$data[$i][0]}</li>";
}
}
?>
</ul>
Output:
<ul><li>1.2</li><li>2.5</li><li class="red">4.7</li><li class="red">5.7</li><li class="red">3.5</li><li class="red">7.2</li><li class="red">4.7</li><li class="red">3.5</li></ul>
Ideone Demo
http://ideone.com/s2gdmG

Php add class dynamically to the first and last block

I have an array like this
$products_array = array('test product', 'test new product', 'test lipsum', 'test lorem', ....);
I just got the values from array like this
echo '<ul>';
foreach( $products_array as $product_array ) {
echo '<li>$product_array</li>';
}
echo '</ul>';
But here I want something dynamic. I want to add class name according to the value set by the user. Lets say user wants to show 5 lists in a row then the markup will be like this
<ul>
<li class="first">test product</li>
<li>test new product</li>
<li>test lipsum</li>
<li>test lorem</li>
<li class="last">test update</li>
<li class="first">test new product</li>
<li>test a product</li>
<li>test new lipsum</li>
<li>test lorem</li>
<li class="last">test new update</li>
</ul>
So here you can see at last means after each 5 post its adding class last and it is adding class first to the first list and after the fifith list blocks. So in this when user will set $class = 3 then it will add last class to the third block and the first will be added to the first and the list block just after the 3rd, 6th, 9th etc
I have done like this
$last = '4' //set 4. so for 4th,8th,12th it will add class last. and for 1st, 5th, 9th it will add class first
echo '<ul>';
$i = 0;
$count = count($products_array);
foreach( $products_array as $product_array ) {
$i++;
$class = '';
if( $i == $count ) {
$class = 'last';
}
echo '<li class='.$class.'>$product_array</li>';
}
echo '</ul>';
But its not working. So can somone tell me how to do this? Any help and suggestions will be really appreciable. Thanks
Use a modulus to determine the class to add. The logic goes...
When the remainder is 0, we are on the last item of each group (the nth of n)
When the remainder is 1, we are on the first item of each group (the 1st of n)
Otherwise, we are somewhere in the middle
For example
$last = 4;
?>
<ul>
<?php
foreach ($products_array as $index => $product) :
switch(($index + 1) % $last) { // array indexes are 0-based so add 1
case 0 :
$class = 'last';
break;
case 1 :
$class = 'first';
break;
default :
$class = '';
}
?>
<li class="<?= $class ?>"><?= htmlspecialchars($product) ?></li>
<?php endforeach ?>
</ul>
eval.in demo
This should do the trick. You could also use modulus, but i am not quite sure how it behaves with small perPage-settings.
//your perPage-setting, change this for more elements per page
$perPage = 3;
$count = count($products_array);
//loop over elements
for($i = 1; $i <= $count; $i++) {
$className = "";
if($i / $perPage == 0) {
$className = "last";
} else if((floor($i / $perPage) * $perPage + 1 == $i)
$className = "first";
echo '<li class='.$className.'>'.$product_array[$i-1].'</li>';
}

PHP Simple HTML Dom Parser count specific results?

Right now i am working around one PHP script based on http://simplehtmldom.sourceforge.net/.
Here is my code:
<?PHP
foreach ($html->find('li.tooltip') as $ul) {
$id = $ul->id;
$dt = "data-text";
$dt = "data-text";
$cid = "colvar-id";
$datatext = $ul->$dt;
$colvarid = $ul->$cid;
$countN = count($id);
$number = 1;
$N = $i++;
if ($N == "") {
$N = 0;
}
}
?>
<?PHP echo "Result is: $countN"; ?>
This code is suposed to count the number of founded occurencies, but it displays nothing.
All i want is to count the founded occurencies and simply display the number of occurencies.
Thanks in advance!
You can use count():
$html = str_get_html(<<<EOF
<ul>
<li>not a tooltip</li>
<li class="tooltip">tooltip</li>
<li class="tooltip">also a tooltip</li>
</ul>
EOF
);
echo count($html->find('li.tooltip'));
// 2

Center Logo Inside Dynamic li Navigation

So i have a CMS which uses a foreach loop to generate the navigation which consists of individual list items inside a ul.
Basically what I want is to have my logo inserted in the center of these links, with an equal number of links on either side.
I've got my code to split up into two different columns of navigation with a gap, but I cant figure out where to place the logo div so it doesn't repeat more than once, current code also throws out some empty list items which I don't need.
<ul>
<?php $i = 0; foreach($items as $item): ?>
<li><a<?php ecco($item->isOpen(), ' class="active"') ?> href="<?php echo $item->url() ?>"><?php echo html($item->title());?></a></li>
<?php if (++$i % 3 === 0 && $i !== count($items)) echo "</li><li>"; endforeach ?>
</ul>
Thanks.
How about something like this?
UPDATE
Since your count doesn't work, try this:
<ul>
<?php
$j = 0;
$breakPoint = 0;
foreach($items as $item) {
$j++;
$breakPoint = $j;
}
$i = 0;
foreach($items as $item) { ?>
if ($i === $breakPoint) {
/* insert Logo Code */
} else { ?>
<li><a<?php ecco($item->isOpen(), ' class="active"') ?> href="<?php echo $item->url() ?>"><?php echo html($item->title());?></a></li>
<?php
}
$i++;
} ?>
</ul>
Haven't tested it. And it depends if you have a odd or even number of $item elements.

Limit results in PHP using while loop

I have a list of returned subcategories. I only have access to the template display and not to the MySQL query so no, I can't limit the query.
Right now all the results are returned. I would like to limit the list to 5, and then add a "more" link if there are more than 5 results.
I know I did this wrong because I don't think count is actually tied to the foreach:
<ul class="sub-categories">
<?php
while (count($category->getChildren()) <= 5) { // line I added for while loop
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount())
continue;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
} // line I added for while loop
?>
</ul>
Keep track within the foreach and break; when you've reached the limit:
<ul class="sub-categories">
<?php
$i = 0;
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount()) continue;
$i++; if($i>5) break;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
?>
</ul>

Categories