Php break the ul li - php

I am showing images in php in ul list. I want to show 5 li in my ul then 2 li and after that again 5 li.I am using this code but it is showing 5 li every row.
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$break_after = 5;
$counter = 0;
$totalNumber = count($data);
foreach ($data as $item)
{
if ($counter % $break_after == 0)
{
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after == ($break_after-1) || $counter == $totalNumber-1) {
echo '</ul>';
}
++$counter;
}
dfff
fdfddf
fdfd
ffd
fdfd
fddf
dfdf
fddf
dfdf
dfdf
fddf
fddf
fdfd
fddf
fddf
fdfd
fddf

Hope this solution might help you :
When you want a break after 5,2,5 Y not take that an array array(5,2,5) instead of just break_after=5. break_after=5 will breake the ul at every 5 intervals. I have some change in logic for you :
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$break_after = array(5,2,5);
$counter = 0;
$break_key=0;
$totalNumber = count($data);
foreach ($data as $item){
if ($counter % $break_after[$break_key] == 0){
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after[$break_key] == ($break_after[$break_key]-1) || $counter == $totalNumber-1) {
echo '</ul>';
++$break_key;
$counter = 0;
}else{
++$counter;
}
}
Output for same is :
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
<ul><li>6</li><li>7</li></ul>
<ul><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>

To achieve what you want use the following:
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22);
$total = count($data);
foreach ($data as $index => $item)
{
if ($index == 0 || $index == 5 || $index == 7 || ($index > 8 && ($index - 2) % 5 == 0))
{
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($index == 4 || $index == 6 || $index == $total - 1 || ($index > 6 && ($index - 2) % 5 == 4)) {
echo '</ul>';
}
}

Pretty much the same answer as varunsinghal and Vivek Tankaria, but refactored to separate the logic and the view:
<?php
$pattern = [5, 2, 5, 5];
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
if (count($data) < array_sum($pattern)) {
throw new Exception('Please provide at least the same amount of data as lines required in the pattern');
}
?>
<?php foreach ($pattern as $limit): ?>
<ul>
<?php for ($i = 0; $i < $limit; $i++): ?>
<li><?= $data[$i]; ?></li>
<?php endfor; ?>
</ul>
<?php endforeach; ?>

For multiple values in array.
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36);
$break_after = array(5,2,5);
$counter = 0;
$break_key=0;
$totalNumber = count($data);
foreach ($data as $item){
if ($counter % $break_after[$break_key] == 0){
echo '<ul>';
}
echo '<li>'.$item.'</li>';
if ($counter % $break_after[$break_key] == ($break_after[$break_key]-1)) {
echo '</ul>';
++$break_key;
if(count($break_after)==($break_key)){
$break_key=0;
}
$counter = 0;
}else{
++$counter;
}
}
?>

You can try this logic
<?php
$data = array(1,2,3,4,5,6,7,8,9,10,11,12);
$breakPoint=4;
$ct=1;
echo '<ul>';
foreach($data as $k=>$v){
echo '<li>'.$v.'</li>';
if($breakPoint == $k && $ct==1){
$breakPoint=$breakPoint+2;
$ct=2;
echo '</ul><br/><ul>';
}elseIf($breakPoint == $k && $ct==2){
$breakPoint=$breakPoint+5;
$ct=1;
echo '</ul><br/><ul>';
}
}
echo '</ul>';
?>
Output:
1
2
3
4
5
6
7
8
9
10
11
12

First break is at 5 so $i will be 4 then 2 elements more so $i will be 6. After this the break is required after every 5 elements, so we have 5+2+5 = 12 elements which gives $i=11 So similarly other break points will be 11 16 21 26 31 36 and so on.
<ul>
<?php
$i=0;
foreach($data as $item){
echo '<li>'.$item.'</li>';
if($i==4 || $i==6 || $i==11 || $i==16 || $i==21 || $i==26){
echo '</ul><ul>';
}
$i++;
}
?>
</ul>

Related

PHP, generate previous and next links from array with numbers

I have an array like this:
$pages = (1, 29, 209, 389, 440, 527)
And I want to make simple HTML navigation through these pages. Only 'first', 'last', 'prev' and 'next' links.
And when I click the 'next'/'prev' link they had to change accordingly.
E.g. when I am at page 389 prev and next to be 209 and 440. If I am at page 440 prev and next to be 389 and 527.
Here is one simple approach:
$pages = array(1, 29, 209, 389, 440, 527);
$current = isset($_GET['page']) ? $_GET['page'] : $pages[0];
// current page
$key = array_search($current, $pages);
echo 'current page: ' . $pages[$key] . '<br />';
// previous page
$prev = $key - 1;
if ($prev >= 0 && $prev < count($pages)) {
echo 'prev | ';
} else {
echo 'prev | ';
}
// next page
$next = $key + 1;
if ($next >= 0 && $next < count($pages)) {
echo 'next';
} else {
echo 'next';
}
Assuming the keys will always be in order, then the first page will always be at $pages[0], and to get the last you could use $pages[key(array_slice($pages, -1, 1, true))]
function printPager($pageList,$currentPage)
{
$links="";
if(($currentIndex = array_search($currentPage, $pageList))!== NULL)
{
$links .=
//first
($currentIndex!=0?"<a href='/".($pageList[0])."'>First</a> ":"") .
//prev
(isset($pageList[$currentIndex-1])?"<a href='/".($pageList[$currentIndex-1])."'>Prev</a> ":"").
//next
(isset($pageList[$currentIndex+1])?"<a href='/".($pageList[$currentIndex+1])."'>Next</a> ":"").
//last
($currentIndex!=count($pageList)-1?"<a href='/".($pageList[count($pageList)-1])."'>Last</a>":"");
}
echo $links;
}
printPager(array(20,4,10,14),20);
try this:
<?php
$pages = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$active = 1;
$last = false;
$next = false;
if (isset($_GET['page']))
{
$active = $_GET['page'];
$last = $active - 1;
$next = $active + 1;
if (!in_array($next, $pages))
{
$next = false;
}
if (($last < 0) or !in_array($last, $pages))
{
$last = false;
}
}
?>
<ul>
<li>
<- LAST
</li>
<?php foreach ($pages as $page): ?>
<li><?= $page ?> <?= $page == $active ? ' is active!' : ''?></li>
<?php endforeach; ?>
<li>
NEXT ->
</li>
</ul>
<ul>
<?php
$pages = [1,4,89,100,121,224,443,527];
$thisPage = $_GET['page'];
foreach($pages as $key => $page){
if($thisPage == $page){
$thisPageKey = $key;
}
}
foreach($pages as $key => $page){
if($key==0){
echo '<li>first</li>';
}
if($key+1==count($pages)){
echo '<li>last</li>';
}
if(array_key_exists($thisPageKey-1, $pages) && $thisPage == $page){
echo '<li>prev</li>';
}
if(array_key_exists($thisPageKey+1, $pages) && $thisPage == $page){
echo '<li>next</li>';
}
}
?>
</ul>
You could try this
$pages=array(1, 29, 209, 389, 440, 527);
foreach ( $array_keys=array_keys($pages) as $array_keys) {
$pages_invert[ $pages[$array_keys] ]=$array_keys;
}
echo 'first ('.$pages[0].')';
echo ' | ';
if( $pages_invert[$_GET['page_id']]-1 >= 0 ) echo 'previous ('.$pages[$pages_invert[$_GET['page_id']]-1].') ';
else echo 'previous';
echo ' | ';
echo 'current ('.$_GET['page_id'].')';
echo ' | ';
if( $pages_invert[$_GET['page_id']]+1 <= 5 ) echo 'next ('.$pages[$pages_invert[$_GET['page_id']]+1].')';
else echo 'next';
echo ' | ';
echo 'last ('.$pages[count($pages)-1].')';
The foreach command makes inversion of your original array for jumps from current to previous and next array keys at $pages array.
To preview how the arrays looks, put this code:
any line arter your $pages array definition
<?
echo '<pre>';
print_r($pages);
echo '</pre>';
echo '<pre>';
print_r($pages_invert);
echo '</pre>';
?>
Please notice the minimum items in the $pages array is 3 items.

Create list per 4 records [duplicate]

This question already has answers here:
display data in multiple columns
(3 answers)
Closed 8 years ago.
I am trying to create multi-list of records with 4 records per list without knowing how many records there are. However, I cannot figure out how to handle the math. I manually typed in $n == 5 || $n == 9 etc knowing it is stipud and cannot exactly solve the problem. Can anyone help me how to handle that. Also, the lists underneath works well only if the total number of records cannot be evenly divided by 4. If it can, it will create a blank list at the end.
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 1
$row_cnt = $result->num_rows;
$total_lists = round($row_cnt / 4, 0);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
echo "<li>$row['something']</li>";
if ($n == 5 || $n == 9 || $n == 13 || $n == 17 || $n == 21 || $n ==25 || $n ==29 || $n == 33 || $n == 37 || $n == 41 || $n == 45 || $n == 49 || $n == 53 || $n == 57 || $n == 61 || $n == 65 || $n == 69 || $n == 73 || $n == 77){
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
$n = $n + 1;
}
echo "</ul>";
}
Thanks in advance for the help. :)
SOLVED:
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 0
$row_cnt = $result->num_rows;
$total_lists = ceil($row_cnt / 4);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
$n++;
echo "<li>$row['something']</li>";
if ($row_cnt > 4) {
if ($n % 4 === 0) {
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
}
}
echo "</ul>";
}
You're actually not too far off track from what you might want to be doing, you just need to use one additional tool to accomplish it: the % or modulus operator.
The modulus operator will return the remainder of division problem:
$x = 5 % 2; // 1
Looking at your logic, your action needs to be taken when your incrementer ($n) minus 1 divided by 4 would have a remainder of 0:
if (($n - 1) % 4 === 0)
{
//your <ul> insertion could go here.
}
Here's a link to the PHP manual page discussing mathematical operators:
http://us1.php.net/manual/en/language.operators.arithmetic.php
Alternatively, you could use a simple array_chunk() on your db results. Provide the proper grouping (in this case by four's) to it and them loop them thru foreach. Consider this example:
// dummy data (values from db)
$values_from_db = array(
array('id' => 1, 'something' => 'list1'),
array('id' => 2, 'something' => 'list2'),
array('id' => 3, 'something' => 'list3'),
array('id' => 4, 'something' => 'list4'),
array('id' => 5, 'something' => 'list5'),
array('id' => 6, 'something' => 'list6'),
array('id' => 7, 'something' => 'list7'),
array('id' => 8, 'something' => 'list8'),
array('id' => 9, 'something' => 'list9'),
);
$values_from_db = array_chunk($values_from_db, 4); // group them by four's
?>
<?php foreach($values_from_db as $key => $value): ?>
<ul style="list-style-type: none;">
<?php foreach($value as $index => $element): ?>
<li><?php echo $element['id'].'.'.$element['something']; ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>

modulus loop calculation of non even numbers

I need to wrap my html output with <ul> tags.
Using modulus i can start the opening tags (every 4th) using
if( $i==0 || $i % 4==0 )
but for the closing </ul> i need a pattern of 3, 7, 11, 15, 19 etc..
here is my attempt if ( $i!=0 && (($i-1) % 4 == 0 || $i==$max-1) )
full code
$str = '';
$i = 0;
$max = count($value['title']);
foreach ($value['title'] as $key2){
//if( $i==0 || $i==4 || $i==8 || $i==12 || $i==16 )
if( $i==0 || $i % 4==0 )
$str .= "<ul>";
$str .= "<li><a href='#'>$key2</a></li>";
if( $i==3 || $i==7 || $i==11 || $i==15 || $i==19 || $i==$max-1)
//if ( $i!=0 && (($i-1) % 4 == 0 || $i==$max-1) )
//if( $i!=0 || $i % 3==1 || $i==$max-1)
$str .= "</ul>";
$i++;
}
echo $str;
after posting the question, i got it by changing the minus to a plus if ( $i!=0 && (($i+1) % 4 == 0 || $i==$max-1) )
I prefer to use to use implodes on arrays myself, but this will do things the way you were heading.
echo '<ul>';
foreach ( $array as $key => $value ) {
echo "<li><a href='#'>$value</a></li>";
if ( 3 === $key % 4 ) {
echo '</ul><ul>';
}
}
echo '</ul>';
I don't like this method because it means when the array has a multiple of four items there will be an empty ul tag. Could make a difference or not, but I think its sloppy.
Instead my I suggest:
$list = '';
foreach ( $array as $key => $value ) {
$list .="<li><a href='#'>$value</a></li>";
if ( 3 === $key % 4 ) {
echo "<ul>$list</ul>";
$list = '';
}
}
if ( $list ) {
echo "<ul>$list</ul>";
}
Something like this
$value['title'] = range(0, 100);
$max = count($value['title']);
$i = 0;
$count = 4;
$str = '';
foreach ($value['title'] as $key2)
{
if ($i % $count == 0)
$str .= "<ul>" . PHP_EOL;
$str .= "<li><a href='#'>$key2</a></li>" . PHP_EOL;
if ($i % $count == $count - 1 || $i == $max - 1)
$str .= "</ul>" . PHP_EOL;
$i++;
}
echo $str;
http://3v4l.org/f6cAl

3 Div column classes from a Foreach

I'd like to get this code to actually work.
What I'm trying to get is my items separated into 3 columns.
I would also like to call the columns "first", "second", and "third", instead of
class0, class1 and class2
This code isn't working since all my items get called class0
<?php
$count = 0;
foreach ($this->items as $item) {
$count = $count == 3 ? 0 : $count++;
?>
<div class="<?php echo "class".$count ?>">
No need for the == 3 test, a simple:
<div class="classs<?php echo $count++ % 3?>">
would do the trick. Modulo math:
$count = 0 -> 0 % 3 = 0
$count = 1 -> 1 % 3 = 1
$count = 2 -> 2 % 3 = 2
$count = 3 -> 3 % 3 = 0
$count = 4 -> 4 % 3 = 1
etc...
You code is not working because $count++ is returning count's first FIRST, then incrementing the value. But since that original value is returned and assigned back to $count, you continually assign 0 over and over and over.
If you'd done ++$count, then it would have worked. (increment THEN return the new value)
This should work:
<?php
$count = 0;
$names = ['first','second','third'];
foreach ($this->items as $item) :
?>
<div class="class-<?=$names[$count++%3] ?>">
<?php
endforeach;
?>
You can use any of these codes:
1st way:
<?php
$count = 0;
foreach ($this->items as $item) {
$count = $count == 3 ? 0 : $count++;
switch ($count){
case 1: echo "<div class='first' >";break;
case 2: echo "<div class='second' >";break;
case 3: echo "<div class='third' >";break;
}
}
?>
2nd way:
<?php
$count = 0;
$name = null;
foreach ($this->items as $item) {
$count = $count == 3 ? 0 : $count++;
$name = ($count == 1 ) ? 'first': ( $count == 2 ) ? 'second': 'third';
}
?>
<div class="<?php echo $name ?>" >
You can use arrays with hard coded values like :
<?php
$numbers = array('first','second','third');
foreach ($this->items as $item):
$count = $count == 3 ? 0 : $count++;
?>
<div class="<?php echo "class_".$numbers[$count] ?>">
<?php endforeach; ?>
<?php
$count = 0;
foreach ($this->items as $item) {
if ($count==0) {
$class = "first";
$count++;
} else if ($count==1) {
$class = "second";
$count++;
} else {
$class = "third";
$count = 0;
}
?>
<div class="<?php echo $class ?>">
Something like this should work though a select case may be quicker

PHP - If number is divisible by 3 and 5 then echo

I'm new to PHP and trying to create the following whilst minimizing the amount of code needed. PHP should show a list of 100 then display if the number is / by 3, 5 or 3 and 5. If not by any then show nothing.
This is what I've got so far, but any help would be great since not sure about the / by 3 and 5 bit as you can see below.
<?php $var = range(0, 100); ?>
<table>
<?php foreach ($var as &$number) {
echo " <tr>
<td>$number</td>
<td>";
if($number % 3 == 0) {
echo "BY3";
} elseif ($number % 5 == 0) {
echo "BY5";
} elseif ($number % 3 and 5 == 0) {
echo "BY3 AND 5";
}
echo "</td></tr>";
}
?>
</table>
Thanks
Nope... you should check first if it's divisble for 15 (3x5) (or 3 and 5) and after you can do other checks:
if($number % 15 == 0) {
echo "BY3 AND 5";
} elseif ($number % 5 == 0) {
echo "BY5";
} elseif ($number % 3 == 0) {
echo "BY3";
}
echo "</td></tr>";
?>
Because every number divisble for 15 is also divisble for 3 and 5. So your last check could never hit
if I'm reading your question correct then you are looking for :
if ($number % 3 == 0 && $number %5 == 0) {
echo "BY3 AND 5";
} elseif ($number % 3 == 0) {
echo "BY3";
} elseif ($number % 5 == 0) {
echo "BY5";
}
Alternative version :
echo ($number % 3 ? ($number % 5 ? "BY3 and 5" : "BY 3") : ($number % 5 ? "BY 5" : ""));
$num_count = 100;
$div_3 = "Divisible by 3";
$div_5 = "Divisible by 5";
$div_both = "Divisible by 3 and 5";
$not_div = "Not Divisible by 3 or 5";
for($i=0;$i<=$num_count;$i++)
{
switch($i)
{
case ($i%15==0):
echo $i." (".$div_both.")</br>";
break;
case ($i%3==0):
echo $i." (".$div_3.")</br>";
break;
case ($i%5==0):
echo $i." (".$div_5.")</br>";
break;
default:
echo $i."</br>";
break;
}
}
No need to do three if statements:
echo "<table border='1'>";
for ($i = 1; $i <= 100; $i++) {
echo "<tr><td>{$i}</td><td>";
if ($i % 3 == 0) echo "BY3 ";
if ($i % 5 == 0) echo "BY5";
echo "</td></tr>\n";
}
echo "</table>";
Update the code as given below
<?php $var = range(0, 100); ?>
<table>
<?php foreach ($var as &$number)
{
echo " <tr>
<td>$number</td>
<td>";
if($number % 3 == 0 && $number % 5 == 0)
{
echo "BY3 AND 5";
}
elseif ($number % 5 == 0)
{
echo "BY5";
}
elseif ($number % 3 == 0)
{
echo "BY3";
}
echo "</td></tr>";
}
?>
<?php
if($number % 5 == 0 && $number % 3 == 0) {
echo "BY3 AND 5";
} elseif ($number % 5 == 0) {
echo "BY5";
} elseif ($number % 3 == 0) {
echo "BY3";
} else{
echo "NOT BY3 OR 5";
}
?>
if($number % 15 == 0)
{
echo "Divisible by 3 and 5";
}
elseif ($number % 5 == 0)
{
echo "Divisible by 5";
}
elseif ($number % 3 == 0)
{
echo "Divisible by 3";
}
This is neater and completed to be run:
<?php
for ($i = 1; $i <= 100; $i++) {
if ($i % 15 == 0)
{
echo"Divisible by 3 and 5</br>";
}
elseif ($i%3==0)
{
echo"Divisible by 3</br>";
}
elseif ($i%5==0)
{
echo"Divisible by 5</br>";
}
else
{
echo $i,"</br>";
}
}
?>
<?php
for ($i = 1; $i <= 100; $i++) {
if ($i % 15 == 0) echo "This Number is Divisible by 3 and 5<br>";
else if ($i % 3 == 0) echo "This Number is Divisible by 3 only<br>";
else if ($i % 5 == 0) echo "This number is Divisible by 5 only<br>";
else{
echo "$i<br>";
}
}
?>

Categories