Introduction
Arrays in PHP allow you to store multiple values inside a single variable. Instead of creating separate variables for every employee, product, or subject, you can store related information together in an array. PHP arrays are useful for managing student records, employee details, product lists, and sales data. In this chapter, you will learn Introduction to Arrays in PHP how to create, access, update, add, and remove array elements through beginner-friendly solved questions.
Question 1: Create and Display an Indexed Array
Problem Statement
Create an indexed array containing five programming languages and display all values using print_r().
PHP Solution
<?php
$languages = ["PHP", "Python", "Java", "C++", "JavaScript"];
print_r($languages);
?>
Sample Output
Array
(
[0] => PHP
[1] => Python
[2] => Java
[3] => C++
[4] => JavaScript
)
Explanation
An indexed array stores multiple values using numeric indexes. PHP automatically assigns indexes starting from 0.
Here:
- Index
0contains PHP. - Index
1contains Python. - Index
2contains Java. - Index
3contains C++. - Index
4contains JavaScript.
The print_r() function displays the complete array structure.
Concepts Covered
- Indexed arrays
- Array creation
print_r()- Numeric indexes
Question 2: Access Individual Array Elements
Problem Statement
Create an array containing five employee names and display the first, third, and fifth employee names using their indexes.
PHP Solution
<?php
$employees = ["Amit", "Neha", "Rahul", "Priya", "Karan"];
echo "First Employee: " . $employees[0] . "\n";
echo "Third Employee: " . $employees[2] . "\n";
echo "Fifth Employee: " . $employees[4];
?>
Sample Output
First Employee: Amit
Third Employee: Rahul
Fifth Employee: Karan
Explanation
You can access an individual array element by writing its index inside square brackets.
For example, $employees[0] returns the first employee’s name, while $employees[2] returns the third employee’s name.
Remember that PHP array indexes start from 0, not 1.
Concepts Covered
- Accessing array elements
- Array indexes
- Square bracket notation
Question 3: Create an Array Using the array() Function
Problem Statement
Create an array containing five product names using PHP’s array() function and display the products.
PHP Solution
<?php
$products = array(
"Laptop",
"Keyboard",
"Mouse",
"Monitor",
"Printer"
);
print_r($products);
?>
Sample Output
Array
(
[0] => Laptop
[1] => Keyboard
[2] => Mouse
[3] => Monitor
[4] => Printer
)
Explanation
PHP supports two common ways to create indexed arrays:
$products = ["Laptop", "Mouse"];
And:
$products = array("Laptop", "Mouse");
Both create an indexed array. The shorter square bracket syntax is commonly used in modern PHP.
Concepts Covered
array()function- Indexed arrays
- Array initialization
Question 4: Count Array Elements Using count()
Problem Statement
A training institute stores the names of six courses in an array. Write a PHP program to count the total number of courses using count().
PHP Solution
<?php
$courses = [
"Python",
"PHP",
"Java",
"Web Development",
"Data Analytics",
"Advanced Excel"
];
$totalCourses = count($courses);
echo "Total Courses: " . $totalCourses;
?>
Sample Output
Total Courses: 6
Explanation
The count() function returns the number of elements in an array.
Here, the $courses array contains six course names, so count($courses) returns 6.
This function is useful when you need to know how many records an array contains.
Concepts Covered
count()- Array length
- Counting elements
Question 5: Update an Existing Array Element
Problem Statement
A company stores the names of four employees. The second employee’s name is incorrect. Update "Neha" to "Neha Sharma" and display the updated array.
PHP Solution
<?php
$employees = ["Amit", "Neha", "Rahul", "Priya"];
$employees[1] = "Neha Sharma";
print_r($employees);
?>
Sample Output
Array
(
[0] => Amit
[1] => Neha Sharma
[2] => Rahul
[3] => Priya
)
Explanation
You can update an array element by assigning a new value to its existing index.
Here, $employees[1] originally contains "Neha". Assigning "Neha Sharma" replaces the old value at index 1.
The other array elements remain unchanged.
Concepts Covered
- Updating array elements
- Array indexes
- Value assignment
Question 6: Add New Elements to an Array
Problem Statement
Create an array containing three product names. Add two more products, "Monitor" and "Printer", using the [] syntax.
PHP Solution
<?php
$products = ["Laptop", "Keyboard", "Mouse"];
$products[] = "Monitor";
$products[] = "Printer";
print_r($products);
?>
Sample Output
Array
(
[0] => Laptop
[1] => Keyboard
[2] => Mouse
[3] => Monitor
[4] => Printer
)
Explanation
You can add new elements to the end of an indexed array by using empty square brackets.
PHP automatically assigns the next available integer index.
For example, after three elements with indexes 0, 1, and 2, the new elements receive indexes 3 and 4.
Concepts Covered
- Adding array elements
- Empty square bracket syntax
- Automatic indexing
Question 7: Remove an Array Element Using unset()
Problem Statement
A company maintains a list of five products. Remove "Mouse" from the array using unset() and display the updated array.
PHP Solution
<?php
$products = ["Laptop", "Keyboard", "Mouse", "Monitor", "Printer"];
unset($products[2]);
print_r($products);
?>
Sample Output
Array
(
[0] => Laptop
[1] => Keyboard
[3] => Monitor
[4] => Printer
)
Explanation
The unset() function removes an array element or variable.
Here, unset($products[2]) removes the element at index 2, which contains "Mouse".
Notice that the remaining indexes are not automatically renumbered. The array keeps indexes 0, 1, 3, and 4.
Concepts Covered
unset()- Removing array elements
- Array indexes
Question 8: Display All Array Elements Using foreach
Problem Statement
Create an array containing five student names and display each name on a separate line using a foreach loop.
PHP Solution
<?php
$students = ["Rahul", "Priya", "Amit", "Neha", "Karan"];
foreach ($students as $student) {
echo $student . "\n";
}
?>
Sample Output
Rahul
Priya
Amit
Neha
Karan
Explanation
The foreach loop is used to access every element of an array without manually writing its index.
In each iteration:
- PHP takes the next array value.
- The value is stored in
$student. - The
echostatement displays the name.
The loop automatically stops after processing all array elements.
Concepts Covered
foreachloop- Accessing array values
- Displaying array elements
Question 9: Check Whether an Array Is Empty
Problem Statement
Create an empty array named $employees. Check whether the array contains any elements using empty().
PHP Solution
<?php
$employees = [];
if (empty($employees)) {
echo "Employee array is empty.";
} else {
echo "Employee records are available.";
}
?>
Sample Output
Employee array is empty.
Explanation
The empty() function checks whether a variable is empty or does not contain a usable value.
An empty array returns true when checked with empty().
This is useful when checking whether a list contains records before displaying or processing it.
Concepts Covered
- Empty arrays
empty()function- Conditional statements
Question 10: Calculate Total Sales From an Array
Problem Statement
A company stores the daily sales amounts for five days in an array. Calculate the total sales and display the result.
Sales data:
| Day | Sales |
|---|---|
| Monday | 5000 |
| Tuesday | 7500 |
| Wednesday | 6200 |
| Thursday | 8000 |
| Friday | 7300 |
PHP Solution
<?php
$sales = [5000, 7500, 6200, 8000, 7300];
$totalSales = 0;
foreach ($sales as $amount) {
$totalSales = $totalSales + $amount;
}
echo "Total Weekly Sales: ₹" . number_format($totalSales);
?>
Sample Output
Total Weekly Sales: ₹34,000
Explanation
The sales amounts are stored in an indexed array.
The foreach loop processes each amount and adds it to $totalSales.
The calculation is:
5000 + 7500 + 6200 + 8000 + 7300 = 34000
Finally, number_format() adds a comma separator to make the total easier to read.
Concepts Covered
- Numeric arrays
foreachloop- Accumulating totals
number_format()- Sales calculations
Key Takeaways
- Arrays store multiple values inside a single variable.
- Indexed arrays use numeric indexes starting from
0. - PHP supports both
[]andarray()syntax for creating arrays. - Use
$array[index]to access an individual element. - Use
count()to count the number of array elements. - Assign a new value to an index to update an element.
- Use
$array[]to add a new element at the end. - Use
unset()to remove an element. - Use
foreachto process all array values. - Use
empty()to check whether an array is empty. - Arrays are useful for managing student records, employees, products, and sales data.
Frequently Asked Questions
1. What is an array in PHP?
An array is a variable that can store multiple values. For example, one array can store several employee names, product prices, or student marks.
2. How many types of arrays are available in PHP?
PHP supports three main types of arrays:
- Indexed arrays
- Associative arrays
- Multidimensional arrays
3. How do you create an array in PHP?
You can create an array using square brackets or the array() function.
Example:
$colors = ["Red", "Green", "Blue"];
4. What is an indexed array?
An indexed array stores values using numeric indexes. PHP normally starts assigning indexes from 0.
5. How can you access an array element?
Use the array name followed by the required index inside square brackets.
Example:
echo $colors[0];
6. Which function counts array elements in PHP?
The count() function returns the total number of elements in an array.
7. How do you add an element to an array?
Use empty square brackets to add a new element at the end.
Example:
$colors[] = "Yellow";
8. How do you remove an element from an array?
Use the unset() function with the element’s index.
Example:
unset($colors[1]);
9. What is the use of foreach in PHP arrays?
The foreach loop accesses each array element one by one. It is commonly used to display or process all array values.
10. What happens to array indexes after using unset()?
The removed index is not automatically replaced. Other elements keep their existing indexes. You can use array_values() if you want to create a new sequentially indexed array.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
