Arrays in PHP – Storing Multiple Values

What is an Array in PHP?

An array in PHP is a data structure used to store multiple values in a single variable. Instead of creating separate variables for each value, arrays group them together — which makes code more organized and scalable.

For example:

PHP
$language1 = "PHP";
$language2 = "JavaScript";
$language3 = "Python";

This can be replaced by:

PHP
$languages = ["PHP", "JavaScript", "Python"];

Types of Arrays in PHP

1. Indexed Arrays

Arrays with numeric keys (starting at 0).

2. Associative Arrays

Arrays where keys are named (strings instead of numbers).

3. Multidimensional Arrays

Arrays that contain other arrays inside them.

1. Indexed Arrays in PHP

Creating an Indexed Array:

PHP
$colors = array("Red", "Green", "Blue");

or (short syntax):

PHP
$colors = ["Red", "Green", "Blue"];

Accessing Elements:

PHP
echo $colors[0]; // Output: Red

Looping Through:

PHP
foreach ($colors as $color) {
  echo "$color<br>";
}

2. Associative Arrays in PHP

Associative arrays use key-value pairs instead of numeric indexes.

Creating an Associative Array:

PHP
$user = [
  "name" => "Jay",
  "email" => "jay@example.com",
  "age" => 28
];

Accessing Elements:

PHP
echo $user["email"]; // Output: jay@example.com

Looping Through:

PHP
foreach ($user as $key => $value) {
  echo "$key: $value<br>";
}

3. Multidimensional Arrays in PHP

A multidimensional array holds one or more arrays inside another.

Example:

PHP
$students = [
  ["Alice", "PHP", 85],
  ["Bob", "Python", 90],
  ["Charlie", "Java", 78]
];

echo $students[1][0]; // Output: Bob

You can also loop through them using nested loops:

PHP
foreach ($students as $student) {
  echo "Name: " . $student[0] . ", Subject: " . $student[1] . ", Score: " . $student[2] . "<br>";
}

Useful Array Functions in PHP

FunctionDescriptionExample
count()Returns number of elementscount($colors)
array_push()Adds to the endarray_push($colors, "Yellow")
array_pop()Removes from the endarray_pop($colors)
array_shift()Removes first elementarray_shift($colors)
array_unshift()Adds to beginningarray_unshift($colors, "Pink")
in_array()Checks if value existsin_array("Red", $colors)
array_key_exists()Checks if key existsarray_key_exists("name", $user)
implode()Converts array to stringimplode(", ", $colors)
explode()Converts string to arrayexplode(",", "PHP,HTML,CSS")

Real-World Examples

Example 1: Creating a Dropdown from Array

PHP
$languages = ["PHP", "JavaScript", "Python"];

echo "<select>";
foreach ($languages as $lang) {
  echo "<option>$lang</option>";
}
echo "</select>";

Example 2: Display Table from Array

PHP
$products = [
  ["Laptop", 50000],
  ["Mouse", 500],
  ["Keyboard", 800]
];

echo "<table border='1'>";
echo "<tr><th>Product</th><th>Price</th></tr>";

foreach ($products as $product) {
  echo "<tr><td>{$product[0]}</td><td>{$product[1]}</td></tr>";
}

echo "</table>";

Common Mistakes with Arrays

  • Using the wrong index (e.g., accessing $arr[5] when it only has 3 items)
  • Forgetting quotes around associative keys ($user[name] vs $user["name"])
  • Mixing indexed and associative structures without clear logic
  • Not checking if a key exists before using it

Best Practices

  • Use short syntax ([]) for cleaner code
  • Always check for key existence with isset() or array_key_exists()
  • Loop with foreach instead of for unless index is needed
  • Keep array keys consistent (all strings or all integers)
  • Use meaningful keys in associative arrays (e.g., "price", "status")

Notes:

  • Arrays in PHP help store and manage multiple related values
  • Use indexed arrays for lists, associative arrays for labeled data, and multidimensional arrays for table-like data
  • PHP offers many built-in functions to manipulate arrays easily
  • Always use foreach for clean and efficient array iteration

Practice Tasks

Task 1: Favorite Movies
Create an indexed array with 5 favorite movies. Use a loop to display them in an unordered list (<ul>).

Task 2: User Profile
Create an associative array with:

  • Name
  • Age
  • Country
    Print each field with its label.

Task 3: Class Scores Table
Create a 2D array for 3 students:

  • Each student has name, subject, score
    Display in an HTML table using a nested loop.