Introduction to PHP

Arrays

An array holds multiple values in one variable. Indexed arrays use numbers ($subjects = ["HTML", "CSS", "PHP"]), while associative arrays use named keys ($student = ["name" => "Ali", "age" => 20]). foreach loops through every item in an array automatically.

Why this matters

  • ·Stores related data (like a list of subjects) in one place
  • ·foreach removes the need to manually track an index

Common mistakes

  • ·Accessing an index that doesn't exist gives a warning, not an error you can easily miss
  • ·Mixing up array keys ($student["name"]) with numeric indexes causes confusion
Your codePHP
Expected output
HTML
CSS
PHP

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Frequently asked questions

Use the code editor above edit the example freely and check the expected output against your own reasoning.

Practice questions

Question 1

Create an associative array for a student with name and marks keys, then echo both values.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Quick check

Just for this topic answer honestly, then check yourself.

1 / 1

Which loop is commonly used to go through every item in an array?