Let's say I have an external source I'm gathering data from and putting it into list form. This external source can have anywhere from 1 - 100 entries. Let's use rand()
and range()
to represent this. (a minimum of 1, and a random number between 1 and 15 as our total 'entries')
<?php
$max = rand(1, 15);
$range = range(1, $max);
?>
<ul>
<?php
foreach ($range as $number) {
echo '<li>' . $number . '</li>';
}
?>
</ul>
This echo's out like this:
Now let's say I want <li>
to always echo out a total of 10 times.
Even if my list ($number
) is as low as 1, or as high as 15.
If it's 1, it displays the first entry, and then 9 blank <li></li>
(actually, in my code it won't be blank, but will have my own specified text inside. Such as <li>Blank Entry</li>
If it's 15, it displays the first 10 entries, and cuts off the last 5.
I get how I could set the range in my foreach to stop after 10 iterations in the latter example, but how do I account for the blank <li>
listings in the former?
Not sure why this was dinged...just create another array and fill that array with your random values. The other array accepts those values, up to 10, and if the original array has less than 10 values, it populates it with 'blank'.
<?php
$max = rand(1, 15);
$range = range(1, $max);
$arr = [];
for($i=0; $i<=9; $i++){
if(isset($range[$i])){
$arr[] = $range[$i];
}else{
$arr[] = 'blank';
}
}
?>
<ul>
<?php
foreach ($arr as $number) {
echo '<li>' . $number . '</li>';
}
?>
</ul>