Lesson 21 of 50 – PHP Arrays
42%

PHP Arrays

An array is a variable that can store multiple values. Instead of creating separate variables for every item, we can store related values in a single array.

1. What Is an Array?

Consider storing three student names using separate variables.

<?php
$student1 = "Rahul";
$student2 = "Amit";
$student3 = "Priya";

echo $student1;
echo "<br>";
echo $student2;
echo "<br>";
echo $student3;
?>

We can store the same names in a single array.

<?php
$students = ["Rahul", "Amit", "Priya"];

print_r($students);
?>
Output:
Array
(
    [0] => Rahul
    [1] => Amit
    [2] => Priya
)

Arrays make it easier to store, access, and process collections of related data.

2. Creating an Array

In modern PHP, we commonly create arrays using square brackets []. The array() syntax is also supported.

<?php
$colors = ["Red", "Green", "Blue"];

print_r($colors);
?>
Output:
Array
(
    [0] => Red
    [1] => Green
    [2] => Blue
)

Using array():

<?php
$fruits = array("Apple", "Mango", "Banana");

print_r($fruits);
?>

Both approaches create an array. Square bracket syntax is generally preferred in modern PHP examples.

3. Types of Arrays in PHP

PHP arrays commonly appear in three forms:

Type Description Example
Indexed array Uses numeric keys. [10, 20, 30]
Associative array Uses named keys. ["name" => "Rahul"]
Multidimensional array Contains arrays inside an array. [[10, 20], [30, 40]]

These forms are useful for storing lists, records, and structured collections of data.

The next lessons explain each array type in detail.

4. Accessing Array Elements

PHP arrays use keys to access their elements. For a normal indexed array, the first key is 0.

<?php
$fruits = ["Apple", "Mango", "Banana"];

echo $fruits[0];
echo "<br>";
echo $fruits[1];
echo "<br>";
echo $fruits[2];
?>
Output:
Apple
Mango
Banana

You can also store an array element in a variable.

<?php
$numbers = [100, 200, 300];

$firstNumber = $numbers[0];

echo $firstNumber;
?>
Output:
100

Accessing a key that does not exist may produce a warning. Make sure the key exists before using it.

5. Adding Elements to an Array

We can add elements to an indexed array using the square bracket append syntax.

<?php
$fruits = ["Apple", "Mango"];

$fruits[] = "Banana";
$fruits[] = "Orange";

print_r($fruits);
?>
Output:
Array
(
    [0] => Apple
    [1] => Mango
    [2] => Banana
    [3] => Orange
)

Using array_push():

<?php
$numbers = [10, 20];

array_push($numbers, 30, 40);

print_r($numbers);
?>
Output:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)

Use $array[] = $value to append one element, or array_push() to append one or more values.

6. Counting Array Elements

The count() function returns the number of elements in an array at its top level.

<?php
$students = ["Rahul", "Amit", "Priya", "Neha"];

echo count($students);
?>
Output:
4

Example: Use count() in a loop

<?php
$numbers = [10, 20, 30, 40];

for ($i = 0; $i < count($numbers); $i++) {
    echo $numbers[$i] . "<br>";
}
?>
Output:
10
20
30
40

For nested arrays, count() counts only the outer elements by default. The COUNT_RECURSIVE mode counts nested elements as well.

7. Displaying Array Elements with foreach

The foreach loop is one of the easiest ways to process every element in an array.

<?php
$subjects = ["English", "Hindi", "Math", "Computer"];

foreach ($subjects as $subject) {
    echo $subject . "<br>";
}
?>
Output:
English
Hindi
Math
Computer

We can also access each key and value.

<?php
$marks = [
    "English" => 80,
    "Math" => 90,
    "Computer" => 95
];

foreach ($marks as $subject => $mark) {
    echo $subject . ": " . $mark . "<br>";
}
?>
Output:
English: 80
Math: 90
Computer: 95

Learn more about foreach in the previous lesson php_foreach_loop.php.

8. Checking Whether an Element Exists

The in_array() function checks whether a value exists in an array.

<?php
$fruits = ["Apple", "Mango", "Banana"];

if (in_array("Mango", $fruits)) {
    echo "Mango is available";
} else {
    echo "Mango is not available";
}
?>
Output:
Mango is available

By default, the comparison is not strict. Pass true as the third argument to require both value and type to match.

<?php
$values = [10, 20, "30"];

var_dump(in_array(30, $values));
echo "<br>";
var_dump(in_array(30, $values, true));
?>
Output:
bool(true)
bool(false)

Strict checking is useful when the difference between numbers and numeric strings matters.

9. Practical Example: Student Marks

We can store student marks in an array, calculate their total, and find their average.

<?php
$marks = [80, 75, 90, 85, 70];

$total = array_sum($marks);
$numberOfSubjects = count($marks);

$average = $total / $numberOfSubjects;

echo "Total Marks: " . $total . "<br>";
echo "Subjects: " . $numberOfSubjects . "<br>";
echo "Average Marks: " . $average;
?>
Output:
Total Marks: 400
Subjects: 5
Average Marks: 80

Here, array_sum() adds the values in the array, and count() returns the number of subjects.

Practice Assignments
  1. Create an array of five student names and display it using print_r().
  2. Create an array of five numbers and display the third element.
  3. Add two new fruits to an existing array.
  4. Count the number of elements in an array using count().
  5. Display all elements using foreach.
  6. Check whether "PHP" exists in an array using in_array().
  7. Calculate the total and average of five student marks.
  8. Create an array containing numbers and find their sum using array_sum().

🧠 Quick Quiz

1. Which function counts the elements in an array?




2. What is the first index of a normal indexed array?




3. Which function checks whether a value exists in an array?