Arrays are one of the most important data structures in PHP. An array is a variable that can hold multiple values at once, unlike regular variables which can only hold one value. Arrays allow you to store multiple pieces of data under one name, and you can access these values using keys or indices. This makes arrays a fundamental data structure for organizing and managing data efficiently. No, arrays are not just replacements for multiple individual variables. They enable us to build intricate data structures and execute a wide range of operations on this data with great efficiency. No matter the complexity of your data, arrays provide versatile methods for accessing and manipulating it, all while maintaining exceptional speed.
Think of arrays as digital containers that can hold a wide range of data, from simple numbers and text to more complex structures. Whether you're building an online shopping cart, analyzing survey data, or developing a basic database, arrays offer the flexibility you need. Arrays follow the same naming conventions as variables. This means that sometimes it's not immediately obvious in your code whether you're working with a variable or an array. The key syntactic difference lies in how you access individual elements within an array. In this post, we'll delve deep into the different types of arrays in PHP, how to work with them, and their most common applications. You'll learn how to create, populate, sort, search, and manipulate arrays, as well as how to utilize various built-in PHP functions for array operations.
- Indexed (numeric) arrays - These arrays use numeric indexes to store and access values. Indexes start from zero, and each element in the array has its own unique index.
- Associative arrays - These arrays use keys, which are usually strings, to index elements. Instead of numeric indexes, you can use names or other text values as keys.
- Multidimensional arrays - These arrays allow you to store arrays within other arrays, meaning you can work with arrays that have multiple levels.
Using the array() function:$array = array("item1", "item2", "item3");
Using square brackets []:
$numbers = [1, 2, 3, 4, 5];
Adding elements one by one:
$array[0] = "Item1";
$array[1] = "Item2";
$array[2] = "item3";
Now it's time to get down to the practical level and start coding. Let's dive into our PHP tutorial.
manuel@manuel-virtual-machine:~$
sudo apt-get update
manuel@manuel-virtual-machine:~$
sudo apt-get upgrade
manuel@manuel-virtual-machine:~$
clear
manuel@manuel-virtual-machine:~$
cd /opt/lampp
manuel@manuel-virtual-machine:~$
ls
manuel@manuel-virtual-machine:/opt/lampp$
sudo ./manager-linux-x64.run
When the XAMPP manager window opens, start the Apache Web Server and open Visual Studio Code. Click on index.php, then in the code editor panel, modify the following part of the code.
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
<ul>
<li><a href="lessons/lesson01.php">
Lesson 1. - The text printing and comments
</a></li>
<li><a href="lessons/lesson02.php">
</div>
</div>
<!-- footer -->
<?php require_once 'includes/footer.php'; ?>
You can now create a new file called lesson10.php and enter the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 10';
// Includes the header
title
require_once '../includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">
Arrays
</h2>
<!-- The style for <h5> element that changes the font color to blue -->
<style>
h5 {
color: blue;
}
</style>
<div class="container">
<h4>Indexed (numeric) arrays use numeric indexes store and access values.
Indexes start from zero, and each element in the array has its own
unique index.
</h4>
<br/>
<h5>Indexed (numeric) arrays</h5>
<br/>
<?php
// Print one-dimensional
array
echo "<p><strong>One-dimensional array:</strong></p>";
$languages = array("English","German","Serbian","Italian",
"Spanish","French", "Russian");
print_r($languages);
echo "<br/><br/>";
// Print one-dimensional array using a foreach loop
echo "<p><strong>Print
the array using a foreach loop:</strong></p>";
foreach ($languages as $language) {
echo $language . ", ";
}
echo "<br/><br/>";
// Create an array with numbers from 1 to 10
echo "<p><strong>Fill
the array numbers (1-10) using a for loop</strong></p>";
// Create an empty array
$numbers = [];
// Fill the array with numbers from 1 to 10 using a for loop
for ($i=1; $i <= 10; $i++) {
$numbers[] = $i;
}
// Print the contents of the array
foreach ($numbers as $number) {
echo $number . " ";
}
?>
<br/><br/>
</div>
<!-- footer -->
<?php require_once '../includes/footer.php'; ?>
When you run this website, the result will be as in the following image.
Associative Arrays: The Key to Data Organization
Associative arrays are one of the most important data types in PHP and are used in a large number of applications. Their flexibility and readability make them ideal for organizing and managing data. Unlike numerical arrays where elements are indexed by numbers, associative arrays use keys that can be any string or number. This means that instead of accessing an array element by its numerical index, you access it by its unique key. An associative array is declared using the array() function and pairing keys and values using the => operator.
$array = array(
'key1' => 'value1',
'key2' => 'value2',
// ...
);
If you're wondering why we use associative arrays, then as any experienced programmer should know, associative arrays are extremely useful because:
- Better code readability - Keys make the code more readable because they directly indicate the meaning of the data.
- Flexibility - Keys can be any string, allowing data to be organized in various ways.
- Simulating objects: Associative arrays are often used to simulate objects in languages that don't have built-in object support.
- Configuration data - They are often used to store application configuration data.
If this is clear to you, we can now continue with the coding. Add the following code into the lesson10.php file of our project.
<h4>Associative arrays use keys, which are usually strings, to index elements.
Instead of numeric indexes, you can use names or other text values as
keys.
</h4>
<br/>
<h5>Associative arrays</h5>
<br/>
<?php
// Print one-dimensional
array
echo "<p><strong>One-dimensional
array</strong></p>";
$person = array(
"Name"=> "Manuel
Radovanovic",
"Age"=> 49,
"City"=> "Belgrade"
);
print_r($person);
echo "<br/><br/>";
echo "<p><strong>Add
Software Engineer and remove the age:</strong></p>";
// Accessing elements:
echo $person["Name"] . "<br/>";
echo $person["Age"] . "<br/>";
echo $person["City"] . "<br/>";
echo "<br/>";
// Adding a new element:
$person["Occupation"] = "Software
Engineer";
// Removing an element:
unset($person["Age"]);
// Iterating through the array:
foreach ($person as $key => $value) {
echo "$key: $value<br/>";
}
?>
<br/><br/>
When you run this website, the result will be as in the following image.
Indexed Arrays: Building Blocks for Data Organization
Multidimensional arrays are a powerful tool in PHP that allows you to organize and manage complex data efficiently. Essentially, multidimensional arrays are arrays within arrays. Imagine a table with rows and columns. This is a great analogy for a multidimensional array. Each row in the table can be considered an array, and the entire table is then an array of those rows. In PHP multidimensional arrays, indexing starts at 0, you can have more than two dimensions in an array, and interestingly, associative arrays can also be used as elements in multidimensional arrays. Declaring a multidimensional array in PHP is straightforward. Within the outer array, you simply declare inner arrays.
$multidimensionalArray = [
$array1 = array["item1",
"item2", "item3"
… ],
$array2 = array["item1",
"item2", "item3"
… ]
];
<h4>The multidimensional array allow you to store arrays within other arrays,
meaning you can work with arrays that have multiple levels.
</h4>
<br/>
<h5>Multidimensional arrays</h5>
<br/>
<?php
// the two-dimensional
array
$students = array(
array("John", 25, "Math"),
array("Hanna", 22, "English"),
array("Mike", 23, "Science"),
);
// Print two-dimensional array
echo "<p><strong>Two-dimensional
array:</strong></p>";
print_r($students);
?>
<thead>
<tr>
<th>Name</th>
<th>Year</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
<?php
foreach ($students as $student) {
echo "<tr>";
echo "<td>" . $student[0] . "</td>";
echo "<td>" . $student[1] . "</td>";
echo "<td>" . $student[2] . "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<br/>
You can see how this whole process looks like in the following video, too.
And to conclude this lesson, PHP provides many useful built-in functions that you can use to work with arrays. You don't need to know how these functions are programmed, but you can use them. These are the most common:
count($array) - Returns the number of elements in an array.
array_push($array, $value) - Adds a value to the end of an array.
array_pop($array) - Removes and returns the last element from an array.
array_merge($array1, $array2) - Merges two or more arrays into one.
in_array($value, $array) - Checks if a certain value exists in an array.
array_keys($array) - Returns all keys from an associative array.
etc.
No comments:
Post a Comment