dongsui8162
dongsui8162
2017-06-20 19:09

每5个项目对数组中的项目进行分组,并在php中添加短划线

  • foreach
  • for-loop
  • php
  • arrays

I'm building a loop that in my mind will output an array of items divided by a range of 5 numbers. I tried a few function like range, sort, implode, but I haven't found the right solution yet.

So far my code is the following:

foreach (range(0, 100, 5) as $number) {
  echo $number;
  print implode("-", str_split($number));
}

My goal is to output something like:

1-5
5-10
10-15

and so on that I can associate to anything, so essentially a range of numbers every a certain amount of numbers.

Plus I'm not sure if it's the right loop.

I guess I can obtain pretty much the same result with a for loop like:

for($i = 0; $i < 100; $i+=5)
{
     implode("-", str_split($i));
}

Where's my mistake?

UPDATE I probably forget to mention that everything is in a select item:

<select class="drops" name="largesan">
    <option selected value> -- How Many Sandwiches? -- </option><?php
    foreach (range(0, 100, 5) as $numbers)
    {
        $mynumber = $numbers . '-' . $numbers + 5;
        ?>
        <option value="<?php echo $numbers;?>"><?php echo $mynumber;?></option>
        <?php
    }
    ?>
</select>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答