Introduction to Arrays in PHP | Types | Syntax – Example
In PHP, arrays are perhaps the most basic and commonly employed data structure. If you need to store a collection of usernames, a list of product prices, or even configuration settings as key-value pairs, arrays allow for efficient data organisation and manipulation. For a PHP developer, particularly one moving from a procedural paradigm to an object-oriented or more structured approach, it is vital to grasp the concept of arrays.
Focusing on beginners and intermediates, this article embarks on explaining the concept of arrays in PHP—their types and usage—through practical examples.
What Is an Array?
In PHP, an array is a unique variable type that has the ability to store multiple values at once. Rather than creating several variables to hold related pieces of information, a single array can be used to store a collection of such data.
Consider an array as a container with a specific item stored in it that can be accessed using an index or a key. In PHP, arrays can be simple with numerical indexing, associative (key-value) or even multidimensional, containing other arrays as elements.
Syntax
An array can be created by the array() language construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value , ... ) // key may be an integer or string // value may be any value <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?>
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e., “8” will be interpreted as 8, while “08” will be interpreted as “08”). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
A value can be of any PHP type.
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?>
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
Also read: What is a String in C++? Working | Complete Details
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>
Using TRUE as a key will evaluate integer 1 as key. Using FALSE as a key will evaluate integer 0 as key. Using NULL as a key will evaluate the empty string. Using the empty string as the key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
Types of Arrays in PHP
In PHP, there are three types of arrays:
Numeric arrays:
A numeric array is a data structure that allows for storing multiple values in a single variable. It is an ordered collection of elements, each identified by an index number. With PHP’s built-in array functions and operators, programmers can easily manipulate and access the elements within a numeric array.
Numeric arrays in PHP are incredibly versatile as they can hold any type of data, including integers, floats, strings, and even other arrays.
The flexibility of numeric arrays makes them invaluable for organizing and managing large sets of information efficiently. Additionally, PHP offers various methods to add or remove elements from an array dynamically, allowing developers to modify the contents based on their specific requirements.
To create a numeric array in PHP, one simply needs to assign values to the desired indexes within square brackets. For instance: $numbers = [1, 2, 3].
Associative Arrays: Developers can store key-value pairs using the core PHP programming technique known as associative arrays. Associative arrays utilise string or integer keys as opposed to standard arrays, which use numeric indices. Due to their adaptability, they are exceptionally strong and versatile for handling data organisation and manipulation in PHP applications.
In PHP, associative arrays are created using the array() function and assigning values to specific keys. For example, we can create an associative array called $person with keys such as “name”, “age”, and “occupation”. We can then assign values like “John Doe”, 25, and “Developer” respectively to these keys. Accessing the values is as simple as referencing the desired key within square brackets, such as $person[“name”].
Multidimensional Arrays:
Multidimensional arrays, which can store sophisticated data structures, can have more dimensions than normal arrays, which can only have one. Because of this, they are very helpful when handling vast amounts of connected data.
Nesting one or more arrays inside another array results in multidimensional arrays. A separate dimension of the overall structure is represented by each layered array. For instance, a grid of values could be represented as a two-dimensional array with rows and columns acting as the various dimensions. Developers can retrieve or change specific values from the multidimensional array by accessing certain elements using their corresponding indices in each dimension.
Array vs Object in PHP
While all programming languages have data collections such as lists, PHP goes further by having objects with a class-based syntax. Objects and classes are more advanced data types that are preferred for complicated entities that have behaviour (methods) and some state (properties), while arrays are sufficient for simpler types. PHP arrays do render great services, being useful in cases where more appropriate object-oriented configurations would be used in more rigorously typed languages.
Coclusion
In the PHP programming language, arrays are one of the most useful types of data structures as they allow for the effective management of collections of data. Regardless of whether you need to develop a basic script or a sophisticated web application, using arrays will help you to easily and efficiently store, retrieve, and manipulate data. Understanding the various types of arrays—indexed, associative, and multidimensional—will enable you to face different programming problems with confidence.