Forum Moderators: coopster

Message Too Old, No Replies

trouble with a loop?

while loop

         

Matthew1980

10:09 am on May 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello people of webmaster world,

Could anyone shed some light on my problem?

$images_across_cell = "5";

//create array and populate

$img = array('1','2','3','4','5','6','7','8','9','10');

//start building html block code

$data = "<ul>";

//loop through each instance of array

foreach($img as $display_img)
{
$data .= "<li>".$display_img."</li>";

}

//close html block off

$data .= "</ul>";

//$data ready to echo to screen
echo $data;
?>

Each number represents an image, i would like to specify '5' images populating each <li> tag
before the loop starts again, creates the next <li> tag and fills with another '5' images until
the array is exhausted, then exits the loop and closes the <ul> part too. So this example should
get 2 rows of <li></li>tags and opening and closing <ul> tags'

Im just not sure how to do it!

Obviously, if there are no pictures there nothing gets created, but that is just going to be an if
clause..

Thank you in advance.

Matthew

henry0

12:44 pm on May 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This should get you started
review ARRAY_CHUNK() [us2.php.net]

<?php
// example
$arr=array( '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12' );
$chunk= array_chunk($arr,5);
print_r($chunk);
?>

If you try my above example it will result in two chunks of "5 numbers" and a residual chunk of "2 numbers"

ayushchd

6:27 pm on May 23, 2009 (gmt 0)

10+ Year Member



I don't know if this is what you exactly want..but you can try this one out

$images_across_cell = "5";

//create array and populate

$img = array('1','2','3','4','5','6','7','8','9','10','11','12');

$n=12; //no of elements in array

//start building html block code

$data = "<ul>";

//loop through each instance of array
$x=0;
while($x<$n)
{
$data .= "<li>";
$y = $x;
while($y<$x+$images_across_cell)
{
if ($y > $n-1)
break;

$data .= $img[$y];
$y++;
}
$data .= "</li>";
$x = $y;
}
//close html block off

$data .= "</ul>";

//$data ready to echo to screen
echo $data;

Matthew1980

8:24 pm on May 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Henry0 & Ayushchd,

Thank you both for your assistance. I will try both suggestions, and see how I get on & then post to let you know.

Thank you,

Matthew

Matthew1980

9:15 am on May 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello Ayushchd,

Thanks for the help, your code did just the thing i wanted, only altered a little bit to help if 'fit' into where i needed it.

Cheers,

Matthew

ayushchd

9:26 am on May 24, 2009 (gmt 0)

10+ Year Member



Cheers!