show specific data from php array loop

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
neyzo
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Sep 23, 2017 9:04 pm

Thu Sep 28, 2017 11:44 pm

hello, i have this problem where i want to get post from an array and show those posts in a page with pagination where each page can show only 3 posts,so if it is page one,it should show post o-3,page 2 post 4-6 and so on,here is the code:

$total = count($res);
// where $res has the array
$limit=3;
$page=$_REQUEST['p'];
if($page=='')
{
$page=1;
$start=0;
}
else
{
$start=$limit*($page-1);
}
$num_page=ceil($total/$limit);
$startpoint = ($page * $limit) - $limit;
for($x=0; $x<=$total ; $x++)
{
?>
<div id="info">
<?php
echo $res[$x]['message'];
?>
</div>
<br>
<?php
}

function pagination($page,$num_page)
{
echo'<ul style="list-style-type:none;">';
for($i=1;$i<=$num_page;$i++)
{
if($i==$page)
{
echo'<li style="float:left;padding:5px;">'.$i.'</li>';
}
else
{
echo'<li style="float:left;padding:5px;"><a name="next" href="select_post.php?p='.$i.'">'.$i.'</a></li>';
}
}
echo'</ul>';
}
if($num_page>1)
{
pagination($page,$num_page);
}

chorn
php-forum Active User
php-forum Active User
Posts: 405
Joined: Fri Apr 01, 2016 2:18 am

Fri Sep 29, 2017 12:57 am

and what is the problem?

neyzo
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Sep 23, 2017 9:04 pm

Fri Sep 29, 2017 1:20 am

it should show post o-3,page 2 post 4-6 and so on
from the loop.it seems to show all the massages from the array,the data is from an array,where the code is designed for data from the database:

for($x=0; $x<=$total ; $x++)
{
?>
<div id="info">
<?php
echo $res[$x]['message'];
?>
</div>
<br>
<?php
}

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 501
Joined: Mon Feb 22, 2016 5:52 pm

Fri Sep 29, 2017 8:26 am

It seems to show all the messages
That's because you have told it to:

Code: Select all

for($x=0; $x<=$total ; $x++)
Also note: zero is a number in computing, PHP uses zero base indexes - this means that an array starts at 0 unless otherwise told, your script does not reflect this:

Code: Select all

<?php

$array = [1,2,3,4,5,6,7,8,9];

$total = count($array);


for ($x = 0; $x < $total; $x++){
  echo 'Array [', $x, '] = ', $array[$x], '<br>';
}
if you do this:

Code: Select all

<?php

$array = [1,2,3,4,5,6,7,8,9];

$total = count($array);


for ($x = 0; $x <= $total; $x++){
  echo 'Array [', $x, '] = ', $array[$x], '<br>';
}
you should get an error.

Play around with the above scripts so that you do understand what is going on, it is important and can bite you if you don't.


Use [ code ] tags to display your code by using the </> button in the post reply box.

Post Reply