PHP Arrays

Indexed, associative and multidimensional arrays.

✍️ 2 exercises in this lesson

An array stores many values in one variable.

  • Indexed: $cars = ["Civic", "Corolla"]; → $cars[0]
  • Associative: $age = ["Ali" => 25]; → $age["Ali"]
  • Multidimensional: arrays inside arrays.

count() returns the length. Add items with $arr[] = "new"; or array_push(). print_r() displays an array.

Key Takeaways: PHP Arrays

Mastering PHP Arrays helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Arrays Code Example

PHP
<?php
$cars = ["Civic", "Corolla"];
$cars[] = "Alto";

$ages = ["Ali" => 25, "Sara" => 22];
$ages["Usman"] = 30;

$students = [
    ["name" => "Hina", "marks" => 91],
    ["name" => "Bilal", "marks" => 78],
];

echo count($cars) . " cars, first is $cars[0]<br>";
echo "Sara is {$ages['Sara']}<br>";
echo $students[1]["name"] . " scored " . $students[1]["marks"] . "<br>";
print_r($cars);
Output
3 cars, first is Civic
Sara is 22
Bilal scored 78
Array ( [0] => Civic [1] => Corolla [2] => Alto )
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Arrays Practice Exercises

Check what you learned in “PHP Arrays”.

/ 2 solved
Fill in the blank

Count the items in an array.

echo ($cars);
✓ Correct! Not quite. Try again.
Multiple choice

What kind of array is ["Ali" => 25]?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services