Understanding Array In PHP – Create, Read, Add, and Delete

This time, we’ll discuss array in PHP. Array is a kind of data type that will almost certainly be used by the PHP programmers as its flexibility to accommodate data. The array can also hold dozens or even hundreds of data.

The topic about array is very very wide, so it is not possible to discuss all of those in this short article. So, in this short article, we’ll discuss the basic staple of the array and some functions that are frequently used according to the array.

I. Understanding Array In PHP

Array is usually stored in a variable, but began to PHP 7, we can keep the array data in a constant, the discussion here. In order to easy to understand, we can describe an array as a table that has two columns, for example:

Type of Array in PHP

The value of the array can also be shaped an array (become a key of another array) such as the following figure:

Multidimensional Array

In the example above, some values of Vehicle Array ( Car and Motorcycle ) act as an array key of “Car Array” and “Motorcycle Array”. We call this form as a Multidimensional Array, we’ll discuss it later in this article.

II. Writing Array In PHP

In PHP, we can define an array in two ways, by using the array function array() or simply use a square bracket [].

Note that we can use the square brackets only on the PHP Version 5.4 and above. So if we sure that our code will be run on PHP 5.4 and above, then it’s better to use square bracket as it has same pattern with other languages such as Javascript.

Example of defining an array:

<?php
$vehicle = []; // since PHP 5.4
$vehicle = array(); // All version of PHP

1 Indexed Array dan Associative Array


I repeat again, based on its key, array in PHP can be divided into two types: Indexed Array and Associative Array .

Indexed arrays mean that the keys of the array are sequence numbers, such as the example in the previous figure (Tabe 1). Code Example:

<?php
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [0] => Car
    [1] => Motorcycle
    [2] => Bicycle
    [3] => Truck
    [4] => Bus
)*/

In the example above, we know that the index (key) is starting from the number of 0 then followed by 1, 2, etc … 0 for Car, 1 for Motorcycle, etc….

We can change the initial numbers of the index into 1, for example:

$vehicle = [1 => 'Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
/* Result:
Array
(
    [1] => Car
    [2] => Motorcycle
    [3] => Bicycle
    [4] => Truck
    [5] => Bus
)*/

Note that the initial number of the index only allowed to use 0 or 1.

In Addition, We can also define our own index, for example:

$vehicle = ['Car', 'Motorcycle', 5 => 'Bicycle', 'Truck', 'Bus'];

Associative array means that we define our own key for the array, for example:

$user = [ 'id' => 786,  'pass' => 123, 'role' => 'admin' ];

In the example above, We => to pair the key with its value

2 Furthermore: Key And Value In Array


array always consists of key and value either for indexed array or associative array. The term of key is important because we always use it to call the value of the array.

The key is always located on the left side and the value is always located on the right side. For example (taken from the previous):

$user = [ 'id' => 786,  'pass' => 123, 'role' => 'admin' ];

In the above example, the $user variable contains an array, which its keys are: id, pass, and role, while its values are: 786, 123, and admin

While for the indexed array, the key is a sequence number which is by default starts from zero. Consider the following example:

$vehicle = ['Car', 'Motorcycle', 5 => 'Bicycle', 'Truck', 'Bus'];
echo '<pre>'; print_r($vehicle);
/* Result:
Array
(
    [0] => Car
    [1] => Motorcycle
    [2] => Bicycle
    [3] => Truck
    [4] => Bus
)*/

Although it is not stated explicitly, when we print out the array, the key of array is showed up. this keys is important as we’ll use it to get the value of the array, we’ll discuss it later.

3 Multidimensional Array


Array can have the infinite depth, which is often called a multidimensional array can be two-dimension, three, etc. … Multidimensional here means array inside array, the value of an array is the index of another array, in the simple word, the value of the array is also an array.

For example, we translate a multidimensional array as an example in the previous figure:

$vehicle = [
		['Car' => ['merk' => 'Toyota', 'type' => 'Vios', 'year' => '2016']], // value of car become an index
		'Bicycle', 
		'Truck', 
		['Motorcycle' => ['Honda', 'Yamaha', 'Suzuki']], // value of Motorcycle become an index
		'Bus'
	];
echo '<pre>'; print_r($vehicle);

/* Result:
Array
(
    [0] => Array
        (
            [Car] => Array
                (
                    [merk] => Toyota
                    [type] => Vios
                    [year] => 2016
                )

        )

    [1] => Bicycle
    [2] => Truck
    [3] => Array
        (
            [Motorcycle] => Array
                (
                    [0] => Honda
                    [1] => Yamaha
                    [2] => Suzuki
                )

        )

    [4] => Bus
)
*/

III. How to Retrieve Value of Array in PHP

To retrieve/access the value of the array, we use the key of the value by writing the key in a square bracket [], This is applicable to all versions of PHP, for example:

$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
echo $vehicle[1]; // Motorcycle
echo $vehicle[2]; // Bicycle

This is same as Multidimensional array:

$vehicle = [
		['Car' => ['merk' => 'Toyota', 'type' => 'Vios', 'year' => '2016']],
		'Bicycle', 
		'Truck', 
		['Motorcycle' => ['Honda', 'Yamaha', 'Suzuki']],
		'Bus'
	];
echo $vehicle[0]['Car']['merk']; // Toyota
echo $vehicle[1]; // Sepeda
echo $vehicle[3]['Motorcycle']; // Resulted string of "Array" and raise an error as we can't echo an array, use print_r, instead
echo $vehicle[3]['Motorcycle'][1]; // Yamaha

Another way is to use the foreach loop, for example:

$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
echo '
<table>
	<tr>
		<th>Key</th>
		<ht>Value</th>
	</tr>';	
foreach ($car as $key => $value)
{
	echo '<tr>
			<td>'. $key .'</td>
			<td>'. $value .'</td>
		</tr>';
}
echo '</table>';

The result:

Key Value
merk Toyota
type Vios
year 2016

IV. Add/Remove Element of Array in PHP

1 Adding elements to the array


To add an element to the array, simply define a variable/constant followed by a square bracket (either contain a key or not), for example:

<?php
$month 	= ['January'];

// Add elements to array
$month[] 	= 'February'; // PHP will fill the index automatically, increment from the previous index
$month[] 	= 'March';
echo $bulan[2]; // March

Examples for an associative array:

<?php
$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
$car['color'] = 'Silver';
echo '<pre>'; print_r($car);
/* HASIL
Array
(
    [merk] => Toyota
    [type] => Vios
    [year] => 2016
    [color] => Silver
)*/

Furthermore, there are many functions to add elements to the array, please refers to this article.

2 Deleting array element


There are two functions to remove the element of the array, that are: unset and array_slice

Using unset to remove element of array

We use unset if we already know the key of the array, for example:

<?php
// Associative array
$car = ['merk' => 'Toyota', 'type' => 'Vios', 'year' => 2016];
unset($car['type']);
echo '<pre>'; print_r($car);

// Indexed array
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];
unset($vehicle[0]);
echo '<pre>'; print_r($vehicle);

Using array_slice to remove element of array

The second way is to use array_slice function, this function is similar to substr in string functions. array_slice will take some part of the array and delete the rest, for example:

<?php
$vehicle = ['Car', 'Motorcycle', 'Bicycle', 'Truck', 'Bus'];

// We'll take two element, starting from the 2nd element, and remove the rest
$arr = array_slice($vehicle, 1, 2);
echo '<pre>'; print_r($arr);
/* Result
Array
(
    [0] => Motorcycle
    [1] => Bicycle
)*/

In the above example, we take the element of the array starting from the index of 1 (Motorcycle) and take as many as 2 elements. To learn more about the array_slice function, please visit the page: PHP: array_slice – Manual

There are many other functions related to arrays, we use some of them infrequent, the discussions on this topic can be followed in the tutorial: 15+ Most Used PHP Array Functions You Need To Know

Related Post

Leave a comment

Like Us

Social