Nested loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jack12
Forum Newbie
Posts: 3
Joined: Fri Apr 04, 2014 10:21 am

Nested loop

Post by jack12 »

Hi all,

I'm trying to output a nested loop that shows numbers from number 1 being a small font to 12345 being the biggest font but I can't seem to get it working correctly,see attached code.

1 = font 10

12 = font 12

123 = font 14

1234 = font 16

12345 = font 18

Code: Select all

<?php

$sz=array("10px","12px","14px","16px","18px");
for ($i=1;$i<6;$i++) { ?>

<span style="font-size:<?= $sz[$i-1] ?>"><?= $i ?></span><br />


<?php
}


?>

Regards,

Jack
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Nested loop

Post by Celauran »

Works as expected for me, though I'm not seeing a nested loop here. Can you elaborate on what's not working?
jack12
Forum Newbie
Posts: 3
Joined: Fri Apr 04, 2014 10:21 am

Re: Nested loop

Post by jack12 »

hi,

yes it does work but by outputting 12345 from small to big but I'm trying to get it to output 1 12 123 1234 12345 from small to big
see code below.

Code: Select all

for ($I=1;$I<6;$I++)
{
   for ($num = 1; $num<=$I;$num++)
       echo $num;
   echo "<br>";
}
?>
so with the above output code I want it to output
1 = small
12
123
1234
12345 = biggest
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Nested loop

Post by Celauran »

So, this?

Code: Select all

<?php

$sz = array("10px", "12px", "14px", "16px", "18px");
$text = '';
for ($i = 1; $i < 6; $i++): ?>
	<?php $text .= $i; ?>
	<span style="font-size:<?= $sz[$i-1]; ?>"><?= $text ?></span><br>

<?php endfor; ?>
jack12
Forum Newbie
Posts: 3
Joined: Fri Apr 04, 2014 10:21 am

Re: Nested loop

Post by jack12 »

Hi Celauran,

Brilliant, that is what I'm talking about!!!

I just cam across another version which also works.

Code: Select all

$sz = array(
      "1" => "10px",
      "12" => "20px",
      "123" => "30px",
      "1234" => "40px",
      "12345" => "50px"
  );
  
 foreach ($sz as $key => $value)
     {
     echo "<span style=\"font-size:$value\">$key</span><br /> ";
     }
Thanks for the help.much appreciated.

Regards,
J.
Post Reply