Contents
Arrays in PHP
PHP Arrays
PHP Arrays
Arrays in PHP are data structures that allow us to store multiple values under a single variable, whether they are of similar or different data types. This makes it easier to manage large sets of data without needing to create separate variables for each value. Arrays are particularly useful when handling lists, and they provide an easy way to access elements using an index or key.
Types of Arrays in PHP
1. Indexed (or Numeric) Arrays: Arrays that use numeric indices for storing and accessing values.
2. Associative Arrays: Arrays where each value is associated with a user-defined string key, instead of a numeric index.
3. Multidimensional Arrays: Arrays that can contain other arrays within them, making it possible to store complex data structures.
1. Indexed or Numeric Arrays: These arrays use numbers as keys, starting at zero by default. Values can be stored and accessed using these indices. Below are examples to illustrate this concept.
Example 1:
Output:
First array elements:
Cherry
Apple
Orange
Second array elements:
Spinach
Carrot
Pepper
Example 2: Traversing Indexed Arrays Using Loops
Output:
Looping with foreach:
Red
Green
Blue
Yellow
Purple
Total elements: 5
Looping with for loop:
Red
Green
Blue
Yellow
Purple
2. Associative Arrays: Associative arrays use named keys instead of numeric indices, making it possible to create more meaningful associations between keys and values. Below are examples of associative arrays.
Example 1:
"Manager", "Sara"=>"Developer", "Mike"=>"Designer");
// Accessing elements directly
echo "Job of John: " . $people["John"] . "\n"; // Outputs: Manager
echo "Job of Sara: " . $people["Sara"] . "\n"; // Outputs: Developer
echo "Job of Mike: " . $people["Mike"] . "\n"; // Outputs: Designer
?>
Output:
Job of John: Manager
Job of Sara: Developer
Job of Mike: Designer
Example 2: Traversing Associative Arrays
"Project Manager",
"Bob" => "Lead Developer",
"Charlie" => "UX Designer"
);
// Looping through associative array using foreach
echo "Looping with foreach:\n";
foreach ($employee_roles as $name => $role) {
echo "$name's role is $role\n";
}
// Looping using array_keys and for loop
echo "\nLooping with for loop:\n";
$keys = array_keys($employee_roles);
$length = count($employee_roles);
for ($i = 0; $i < $length; $i++) {
echo $keys[$i] . " is a " . $employee_roles[$keys[$i]] . "\n";
}
?>
Output:
Looping with foreach:
Alice's role is Project Manager
Bob's role is Lead Developer
Charlie's role is UX Designer
Looping with for loop:
Alice is a Project Manager
Bob is a Lead Developer
Charlie's role is UX Designer
3. Multidimensional Arrays: These arrays store other arrays within each element, which can be accessed using multiple indices. Below is an example of how to work with multidimensional arrays.
Example 1:
"John", "age" => 20, "grade" => "A"),
array("name" => "Jane", "age" => 22, "grade" => "B"),
array("name" => "Tom", "age" => 21, "grade" => "A")
);
// Accessing elements
echo $students[0]["name"] . " has grade: " . $students[0]["grade"] . "\n";
echo $students[2]["name"] . " is " . $students[2]["age"] . " years old\n";
?>
Output:
John has grade: A
Tom is 21 years old
Associative Arrays in PHP
Associative arrays in PHP allow us to store data in key-value pairs. These arrays provide a more readable way of storing information compared to numerically indexed arrays, especially when the keys represent meaningful labels. For instance, to store the scores of different subjects for a student, using the subject names as keys would be more intuitive than using numbers.
Example:
Below is an example where we create an associative array to store marks for different subjects using the array()
function.
/* First method to create an associative array */
$student_marks = array("Math" => 85, "Science" => 88,
"History" => 90, "English" => 92,
"Art" => 89);
/* Second method to create an associative array */
$student_scores["Math"] = 85;
$student_scores["Science"] = 88;
$student_scores["History"] = 90;
$student_scores["English"] = 92;
$student_scores["Art"] = 89;
/* Accessing elements directly */
echo "Scores for the student are:\n";
echo "Math: " . $student_scores["Math"], "\n";
echo "Science: " . $student_scores["Science"], "\n";
echo "History: " . $student_scores["History"], "\n";
echo "English: " . $student_marks["English"], "\n";
echo "Art: " . $student_marks["Art"], "\n";
?>
Output:
Scores for the student are:
Math: 85
Science: 88
History: 90
English: 92
Art: 89
Traversing the Associative Array:
We can iterate over an associative array using different looping methods. Below are two common ways: using foreach
and for
loops.
Example:
In this example, the array_keys()
function retrieves the keys, and count()
is used to find the number of elements in the associative array.
/* Creating an associative array */
$student_marks = array("Math" => 85, "Science" => 88,
"History" => 90, "English" => 92,
"Art" => 89);
/* Looping through an array using foreach */
echo "Using foreach loop: \n";
foreach ($student_marks as $subject => $marks) {
echo "The student scored ".$marks." in ".$subject."\n";
}
/* Looping through an array using for */
echo "\nUsing for loop: \n";
$subjects = array_keys($student_marks);
$total_subjects = count($student_marks);
for ($i = 0; $i < $total_subjects; ++$i) {
echo $subjects[$i] . ": " . $student_marks[$subjects[$i]] . "\n";
}
?>
Output:
Using foreach loop:
The student scored 85 in Math
The student scored 88 in Science
The student scored 90 in History
The student scored 92 in English
The student scored 89 in Art
Using for loop:
Math: 85
Science: 88
History: 90
English: 92
Art: 89
Mixed-Type Associative Array:
PHP associative arrays can store mixed data types as both keys and values. Below is an example where keys and values are of different types.
Example:
/* Creating an associative array with mixed types */
$mixed_array["name"] = "Alice";
$mixed_array[200] = "Physics";
$mixed_array[15.75] = 100;
$mixed_array["code"] = "XYZ";
/* Looping through the array using foreach */
foreach ($mixed_array as $key => $value) {
echo $key." ==> ".$value."\n";
}
?>
Output:
name ==> Alice
200 ==> Physics
15 ==> 100
code ==> XYZ
Multidimensional arrays in PHP
Multi-dimensional arrays in PHP allow you to store arrays within other arrays. These arrays are useful when you need to manage structured data that goes beyond simple key-value pairs. Common types of multi-dimensional arrays include two-dimensional arrays (like tables) and three-dimensional arrays, which are used to represent more complex structures.
Dimensions of Multi-dimensional Arrays
The number of dimensions in a multi-dimensional array indicates how many indices are needed to access a particular element. For example, a two-dimensional array requires two indices.
Two-Dimensional Array
A two-dimensional array is the simplest form of a multi-dimensional array. It consists of nested arrays, and you can access the elements using two indices. These arrays are often used to store tabular data.
Syntax:
array (
array (elements...),
array (elements...),
...
)
Example:
The following example demonstrates a two-dimensional array containing product names and their prices. The print_r()
function is used to display the structure and content of the array.
Output:
Array
(
[0] => Array
(
[0] => Laptop
[1] => Tablet
[2] => Smartphone
)
[1] => Array
(
[0] => 800$
[1] => 300$
[2] => 500$
)
)
Two-Dimensional Associative Array
A two-dimensional associative array is similar to a regular associative array but allows more complex relationships by using strings as keys. Each key holds another associative array.
Example:
In this example, a two-dimensional associative array is created to store students’ scores in various subjects. The print_r()
function displays the array structure.
array(
"Math" => 85,
"Science" => 90,
"History" => 88,
),
// Mary acts as the key
"Mary" => array(
"Math" => 78,
"Science" => 92,
"History" => 80,
),
// David acts as the key
"David" => array(
"Math" => 90,
"Science" => 87,
"History" => 85,
),
);
echo "Display Scores: \n";
print_r($scores);
?>
Output:
Display Scores:
Array
(
[John] => Array
(
[Math] => 85
[Science] => 90
[History] => 88
)
[Mary] => Array
(
[Math] => 78
[Science] => 92
[History] => 80
)
[David] => Array
(
[Math] => 90
[Science] => 87
[History] => 85
)
)
Three-Dimensional Array
A three-dimensional array is a more complex form of a multi-dimensional array. As the dimensions increase, so does the complexity and the number of indices required to access the elements.
Syntax:
array (
array (
array (elements...),
array (elements...),
),
array (
array (elements...),
array (elements...),
),
)
Example:
The following example demonstrates a three-dimensional array. The array contains product details organized into categories and subcategories. The print_r()
function is used to show the structure.
Output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Laptop
[1] => 20
)
[1] => Array
(
[0] => Tablet
[1] => 30
)
)
[1] => Array
(
[0] => Array
(
[0] => Smartphone
[1] => 50
)
[1] => Array
(
[0] => Headphones
[1] => 100
)
)
)
Accessing Multi-Dimensional Array Elements
You can access elements in multi-dimensional arrays by specifying the indices or keys for each dimension. You can also iterate over the array using loops.
Example:
The following example demonstrates how to access elements of a multi-dimensional associative array that stores employees’ data. Specific elements are accessed using indices, and the entire array is traversed using a foreach
loop.
array(
"Department" => "IT",
"Salary" => 50000,
"Experience" => 5,
),
// Alice will act as a key
"Alice" => array(
"Department" => "HR",
"Salary" => 45000,
"Experience" => 3,
),
// Bob will act as a key
"Bob" => array(
"Department" => "Marketing",
"Salary" => 60000,
"Experience" => 7,
),
);
// Accessing an array element using indices
echo $employees['John']['Salary'] . "\n";
// Iterating over the array using foreach loop
foreach ($employees as $employee) {
echo $employee['Department'] . " " . $employee['Salary'] . " " . $employee['Experience'] . "\n";
}
?>
Output:
50000
IT 50000 5
HR 45000 3
Marketing 60000 7
Sorting Arrays in PHP
Sorting arrays is a common operation in programming, and PHP provides several functions to sort arrays by their values or keys, either in ascending or descending order. You can also define custom sorting rules.
sort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
Output:
Array
(
[0] => 3
[1] => 7
[2] => 12
[3] => 34
[4] => 56
)
Sort Array in Descending Order – rsort()
Function
The rsort()
function sorts an array by its values in descending order, reindexing the array numerically.
Syntax:
rsort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
Output:
Array
(
[0] => 56
[1] => 34
[2] => 12
[3] => 7
[4] => 3
)
Sort Array by Values in Ascending Order – asort()
Function
The asort()
function sorts an array by its values in ascending order while preserving the key-value associations.
Syntax:
asort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
28,
"Alice" => 34,
"Mike" => 22
);
asort($ages);
print_r($ages);
?>
Output:
Hello from PHP!
Sort Array by Values in Descending Order – arsort()
Function
The arsort()
function sorts an array by its values in descending order, preserving the key-value associations.
Syntax:
arsort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
print("Learning PHP is fun!");
Output:
Array
(
[Alice] => 34
[John] => 28
[Mike] => 22
)
Sort Array by Keys in Ascending Order – ksort()
Function
The ksort()
function sorts an array by its keys in ascending order, while maintaining key-value pairs.
Syntax:
ksort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
28,
"Alice" => 34,
"Mike" => 22
);
ksort($ages);
print_r($ages);
?>
Output:
Array
(
[Alice] => 34
[John] => 28
[Mike] => 22
)
Sort Array by Keys in Descending Order – krsort()
Function
The krsort()
function sorts an array by its keys in descending order while maintaining key-value pairs.
Syntax:
krsort(array &$array, int $sort_flags = SORT_REGULAR);
Example:
28,
"Alice" => 34,
"Mike" => 22
);
krsort($ages);
print_r($ages);
?>
Output:
Array
(
[Mike] => 22
[John] => 28
[Alice] => 34
)