5

I am trying to reate an array that contains all the odd numbers between 1 to 20,000. I Use the var_dump() at the end to display the array values without using loops.

For some reason it won't work out.

here's my code so far:

$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);

5 Answers5

9

You need to push the values to your array first:

$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 your array stays empty.

n-dru
  • 9,285
  • 2
  • 29
  • 42
5

This results in alot of undefined indexes because you're not adding anything to $array_variable.

Change the code to this:

   $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 could use:

echo "<pre>";
print_r($array_variable);
echo "</pre>";
Daan
  • 12,099
  • 6
  • 34
  • 51
0

Your $array_variable is empty because you never add any elements to it. Try this instead:

$array_variable = range(1, 20000, 2);
  • range() is a PHP function that generates an array if you give it the start value, the end value, and optionally the increment step. See also http://php.net/manual/en/function.range.php – unfairhistogram Jul 01 '15 at 15:47
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
Nevermore
  • 882
  • 2
  • 18
  • 44
0

You are trying to print an element it does not exist since the array is empty. If you insist on using an array use this code, you notice you assign a value to the array elements: ( and also if you want to display it on a new line in browser, use echo commented out): (if interested about more: 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);
    ?>
Community
  • 1
  • 1
cosmycx
  • 124
  • 1
  • 5