Introduction
In the previous chapter, we learned about variables, data types, operators, and conditionals. These concepts help us store single values and control program flow. In real-world applications, however, we often need to work with multiple values at once and repeat the same task multiple times. This is where arrays and loops become extremely important.
An array allows you to store multiple values inside a single variable, while loops allow you to execute a block of code repeatedly. Together, arrays and loops form the backbone of almost every PHP-based website and web application.
By the end of this chapter, you will be able to:
- Work with one-dimensional and multidimensional arrays
- Understand indexed vs associative arrays
- Perform common array operations
- Use loops to process array data efficiently
What Is an Array?
An array is a special variable that can store multiple values in one container. Instead of creating many variables, you can store all related data in a single array.
Real-world example:
If you want to store the names of all employees in a company, using an array is the best approach.
Indexed Arrays
Indexed arrays store values with numeric indexes, starting from 0.
Creating an Empty Indexed Array
<?php
$the_array = array();
?>
Shortcut syntax:
<?php
$the_array = [];
?>
Creating a Pre-filled Indexed Array
<?php
$students = array("Jill", "Michael", "John", "Sally");
?>
Indexes:
- Jill → 0
- Michael → 1
- John → 2
- Sally → 3
Accessing Array Elements
<?php
echo $students[0]; // Jill
?>
Adding Elements to an Array
Append method:
<?php
$students[] = "Tom";
?>
Using array_push:
<?php
array_push($students, "Tom", "Joey");
?>
Removing an Element
<?php
unset($students[4]);
?>
Updating an Element
<?php
$students[0] = "Jessie";
?>
Associative Arrays
Associative arrays use key-value pairs instead of numeric indexes. They are very useful when data has meaning (like age, name, or location).
Creating an Associative Array
<?php
$michael = array(
"age" => 20,
"gender" => "male",
"favorite_color" => "blue"
);
?>
Accessing Values
<?php
echo $michael['age'];
?>
Adding a New Key-Value Pair
<?php
$michael['occupation'] = 'sales associate';
?>
Removing a Key
<?php
unset($michael['occupation']);
?>
Working with Arrays (Practical Example)
<?php
$myinfo = array("John", 25, "USA", "College");
echo "My name is " . $myinfo[0] . "\n";
echo "I am " . $myinfo[1] . " years old.\n";
echo "I live in " . $myinfo[2] . "\n";
echo "My latest education level is " . $myinfo[3];
?>
Output:
My name is John
I am 25 years old
I live in USA
My latest education level is College
Converting a String into an Array (explode)
The explode() function splits a string into an array.
<?php
$filename = "myexamplefile.txt";
$filename_parts = explode(".", $filename);
echo "Your filename is " . $filename_parts[0];
?>
Converting an Array into a String (implode)
The implode() function joins array elements into a string.
<?php
$filename = "myexamplefile.txt";
$filename_parts = explode(".", $filename);
$filename_parts[0] .= "_v1";
$filename = implode(".", $filename_parts);
echo "Your new filename is " . $filename;
?>
Slicing Arrays (array_slice)
<?php
$fruit = array("apples", "grapes", "oranges", "lemons", "limes");
$smallerFruitArray = array_slice($fruit, 2);
?>
Result: oranges, lemons, limes
Sorting Arrays (ksort)
<?php
$people = array("Jessica" => 35, "April" => 37, "John" => 43, "Tom" => 25);
ksort($people);
?>
This sorts the array by keys in ascending order.
Multidimensional Arrays
Multidimensional arrays are arrays inside arrays.
<?php
$students = array(
"Jill" => array(
"age" => 20,
"gender" => "female"
),
"Amy" => array(
"age" => 25,
"gender" => "female",
"favorite_color" => "green"
)
);
?>
Accessing Multidimensional Data
<?php
echo $students['Jill']['age'];
?>
Updating Values
<?php
$students['Jill']['age'] = 21;
?>
Example: User Profile with Hobbies
<?php
$user = array(
"info" => array(
"name" => "John",
"age" => 27,
"location" => "USA",
"education_level" => "College"
),
"hobbies" => array("Reading", "Coding", "Music")
);
echo "I live in " . $user['info']['location'] . ".\n";
echo "My education level is " . $user['info']['education_level'] . ".\n";
echo "I enjoy " . $user['hobbies'][0] . ", " . $user['hobbies'][1] . ", " . $user['hobbies'][2] . ".";
?>
Introduction to Loops (Concept Overview)
Loops allow you to repeat code automatically. They are commonly used with arrays to process multiple values efficiently.
Common PHP loops:
forwhiledo-whileforeach(most useful with arrays)
Summary
In this chapter, we explored:
- Indexed and associative arrays
- Common array operations
- String-to-array and array-to-string conversions
- Multidimensional arrays
- Real-world PHP examples
Arrays and loops are essential for building dynamic, data-driven PHP applications. In the next chapter, you will learn how to use loops in detail along with advanced array handling techniques.
🚀 Keep practicing and keep building with Cyber Gita