0
<!-- 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]";
        }
        
        ?>
2
  • Shouldn't it be for ($x = 0; $x <= 2; ++$x) ? Commented Sep 23, 2022 at 19:39
  • Do you have any specific question about this code? Commented Sep 26, 2022 at 20:15

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.