PHP: Create an array for a range

后端 未结 4 1302
轮回少年
轮回少年 2020-11-27 08:14

If I have a variable $num = 50 how can I put the numbers 1-50 into an array?

相关标签:
4条回答
  • 2020-11-27 08:53

    This can be solved by using a simple for loop:

    //  Start ↓    End ↓  Step ↓
    for ($i = 1; $i <= $num; ++$i) {
        $array[] = $i;
    }
    
    0 讨论(0)
  • 2020-11-27 09:09

    I think the reason why range() wasn't accepted is that the array needed to start with 1; So:

    $array=range(0,$num);
    unset($array[0]);
    
    0 讨论(0)
  • 2020-11-27 09:13

    Have a look at the documentation for the range() function:

    <?php
    
        $array = range(1, 50);
    
    ?>
    
    0 讨论(0)
  • 2020-11-27 09:16

    Take a look at the range function.

    $array = range(1, $num);
    
    0 讨论(0)
提交回复
热议问题