0

Task:

  1. Use a for loop to build an array (randArray[]) with 50 random integers ranging from 0 - 100.
  2. Use a while loop to build a new array (oddArray[]) with all the odd numbers in randArray[]
  3. Use foreach loop to print all the odd numbers in oddArray[].

I just can't understand why this first step for loop doesn't work

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1-1</title>
</head>
<body>
    <?php
        $randArray= [];
        $value = [];
        for ($randArray= 0; $randArray<= 50; $randArray++) {
                $value = rand(0, 100)
                $randArray[] = $value
            }
        endfor;
        echo ($randArray);
    ?>
</body>
</html>
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49

2 Answers2

0

You can skip a few of them requirements and just handle odd numbers, also rand is not that random..

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1-1</title>
</head>
<body>
    <?php
    for ($i= 0; $i<= 50; $i++) {
        $value = mt_rand(0, 100);

        // odd number
        if ($value % 2 != 0) {
           echo $value.'<br>';
        } 
    }
    ?>
</body>
</html>

Edit (some comments with the syntax issues on original code)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1-1</title>
</head>
<body>
    <?php
    // $randArray set as array, but used as int
    $randArray= [];
    // $value set as array, but used as int
    $value = [];

    // $randArray is now set as an int
    for ($randArray= 0; $randArray<= 50; $randArray++) {
            $value = rand(0, 100) // <-- missing semi-colon + rand not that random, mersenne twister is better
            $randArray[] = $value // <-- missing semi-colon + treating $randArray as an array when its now an int, scala value
        }
    endfor; // whats this?

    // $randArray would be an array so you cant just echo it
    echo ($randArray);

    ?>
</body>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Abiding by the instructions, you can do this

// random and odd arrays
$randArray = [];
$oddArray = [];

// For loop to get 50 random integers and push to randArray
for ($i = 0; $i <= 50; $i++) {
    $value = rand(0, 100);
    $randArray[] = $value;
}

// While loop to get odd numbers from randArray and push to oddArray
$x = 0;
while ($x <= 50) {
    if ($randArray[$x] % 2 == 1) {
        $oddArray[] = $randArray[$x];
    }
    $x++;
}

// Foreach loop to print all odd numbers
foreach($oddArray as $odds) {
    echo $odds . '<br>';
}

Side notes: Use different variables as for loop arguments. That's highly what's causing you errors. You used randArray again for executing for loop

Goma
  • 2,018
  • 1
  • 10
  • 19