user12066439
user12066439

Reputation:

PHP code errors. Need to make use of arrays and for loops

I can tell that I'm making a really silly mistake here. Can someone please help me out by correcting my code? Probably an issue with my loop.

<?php

        $students = array("Sauer Jeppe", "Von Weilligh", "Troy Commisioner", "Paul Krugger", "Jacob Maree");
        $grades = array(75, 44, 60, 62, 70);

        for($i=0; $i<count($students); $i++){

            for($j=0; $j<count($grades); $j++){


                if($grades[$j] >= 70){

                    echo"$students[$i] scored a Distinction.";
                }

                elseif($grades[$j] >= 50){

                    echo"$students[$i] scored a Pass.";
                }

                elseif($grades[$j] >= 0){

                    echo"$students[$i] scored a Fail.";
                }

            }

        }

    ?>

It's meant to display:

Sauer Jeppe scored a Distinction.

Von Weilligh scored a Fail.

Troy Commisioner scored a Pass.

Paul Krugger scored a Pass.

Jacob Maree scored a Distinction.

Thank you.

Upvotes: 0

Views: 573

Answers (1)

u_mulder
u_mulder

Reputation: 54796

There's no need for inner for loop, just take the value from $grades under the same key $i:

for($i=0; $i<count($students); $i++){
    $grade = $grades[$i];
    if($grade >= 70){
        echo"$students[$i] scored a Distinction.";
    } elseif ($grade >= 50){
        echo"$students[$i] scored a Pass.";
    } elseif ($grade >= 0){
        echo"$students[$i] scored a Fail.";
    }
}

Upvotes: 2

Related Questions