How To make 1 to 20 Number Array with for loop

[A]


If you want to create simple 1 to 20 number array with key value then use below code:
<?php
$array = array();
for ($x = 1; $x <= 20; $x++)
{
$array[] = $x;
}
echo "<pre>";
print_r($array);
echo "</pre>";
?>

Or Even More Better.... :)
$array = range(1, 20, 1);
echo "<pre>";
print_r($array );
echo "</pre>";

You can also use below Single line code:
$array = array_combine(range(0,19),range(1,20));

echo "<pre>";
print_r($array);
echo "</pre>";

And of course, If you want your key and value both have 1 to 20 value then use below one:

$array = array_combine(range(1,20),range(1,20));


// Output A

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 13
    [13] => 14
    [14] => 15
    [15] => 16
    [16] => 17
    [17] => 18
    [18] => 19
    [19] => 20
)

[B]


And Also, there is a much simpler way of creating a range of even numbers is by starting with an even number:
$evenarray = range(2, 10, 2);
 echo "<pre>";
 print_r($evenarray);
 echo "</pre>";



// Output B

Array
(
 [0] => 2
 [1] => 4
 [2] => 6
 [3] => 8
 [4] => 10
)

Also you can create your Own function to make your array which start, Ends and increase nth steps as below:
function myRange($start, $limit, $step)
{
     $myArr = array();
     foreach((array) range($start, $limit,$step) as $k => $v)
     {
        $myArr[$k+1] = $v;
     }
     return $myArr;
}
echo "<pre>";
print_r(myRange(0, 100, 10));
echo "</pre>";

// Output B

Array
(
 [1] => 0
 [2] => 10
 [3] => 20
 [4] => 30
 [5] => 40
 [6] => 50
 [7] => 60
 [8] => 70
 [9] => 80
 [10] => 90
 [11] => 100
)

OR use Below Code to start your key with "Zero" Not "one"

function my_range( $start, $end, $step = 1) {

     $range = array();

     foreach ((array)range( $start, $end ) as $index) {
          if (! (($index - $start) % $step) ) {
               $range[] = $index;
          }
     }
     return $range;
}
echo "<pre>";
print_r(my_range(0, 100, 10));
echo "</pre>";


Array
(
    [0] => 0
    [1] => 10
    [2] => 20
    [3] => 30
    [4] => 40
    [5] => 50
    [6] => 60
    [7] => 70
    [8] => 80
    [9] => 90
    [10] => 100
)

Post a Comment

0 Comments