Search code examples
phphtmlfor-loopassociative-array

For loop in php code needs an explanation


<!-- 1- create a new file called lab3.php
           2- add the HTML skeleton code and give its title “Lab Week 3”
           3- open up an php scope
           4- Create an associative array listing favourite subjects. (example: math, english, science and grade for each A+ B+ C-  )
           5- print out for grade english subject
           6- using a for loop print all the items in the array
           --> 
   >
<?php

//Code for associative array

        //data for associated array
        $subjects = [
        "math" => "A+",
        "english" => "B+",
        "science" => "C-",
        
        ]
        
        <br>
    

// Code to print out english grade

        //print out for english grade
        
        echo "My grade in english class is" . $subjects["english"];
        
        <br>
   
// This is my for loop section. If anyone could help me figure this out I'd be greatly appreciated.

        //print out all the items in the array using for loop
        
        for ($x=0; <= 2){
        echo  "$subjects[$x]";
        }
        
        ?>

Solution

  • For all the items in your array use foreach instead:

    foreach ($subjects as $subject => $grade) {
    echo 'My grade in '.$subject. ' is '. $grade . PHP_EOL;
    }
    

    BTW: 1. Don't forget to remove <br> tags in your php code.

    1. You cannot use for loop here, since your array does not have numeric array keys, and if you run for loop in the way you showed in your code, you will get undefined array key warnings.

    Try it online!