Put value for loop inside array

I am trying to create an array containing all the odd numbers from 1to 20,000. I use var_dump()at the end to display array values ​​without using loops.

For some reason this will not work.

here is my code:

$array_variable = array();

for($i=1; $i<=20000; $i++){
    if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
        print_r($array_variable[$i]); // if odd, echo it out and then echo newline for better readability;
    }
}

var_dump($array_variable);
+4
source share
5 answers

You need to first push the values ​​into your array:

$array_variable = array();
for($i=1; $i<=20000; $i++){
   if($i%2 == 1){ 
       $array_variable[] = $i;// or array_push($array_variable, $i);
   }
}
var_dump($array_variable);

Otherwise, the array will remain empty.

+7
source

This results in large undefined indexes because you are not adding anything to $array_variable.

Change the code:

   $array_variable = array();

    for($i=1; $i<=20000; $i++){
      if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
        $array_variable[] = $i; // $array_variable[] means adding something to the array
      }
    }

    var_dump($array_variable); //dump all odd numbers

For better readability of the array, you can use:

echo "<pre>";
print_r($array_variable);
echo "</pre>";
+4
source

$array_variable , . :

$array_variable = range(1, 20000, 2);
0

$array_variable = array();

for($i=1; $i<=20000; $i++){
  if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
      array_push($array_variable, $i); //Push the variable into array
  }
}

var_dump($array_variable); //dump all odd numbers
0

You are trying to print an element that it does not exist, because the array is empty. If you insist on using an array, use this code, you will notice that you assign a value to the elements of the array: (and also if you want to display it on a new line in the browser, use the echo comment): (if you are more interested: what is the difference between echo and print_r

<?php 

        $array_variable = array();

        for($i=1; $i<=20000; $i++){
            $array_variable[$i]=$i;//assignment
            if($i%2 == 1){ // if the remainder after division `$i` by 2 is one{
            print_r($array_variable[$i]); // if odd, echo it out and then echo newline for better readability;
            //echo $array_variable[$i].'<br>';
        }
    }

        var_dump($array_variable);
    ?>
0
source