Arrays in PHP

11 min read

Arrays are an essential concept in PHP. The array is an ordered list of defined values. For example, a list of numbers or a list of text (strings). We can use an array to group the days of the week in a list or all users in our page. In the following, you'll learn how to define arrays, how to work with them, and what important and useful functions exist.

Define arrays

Previously, each variable could only store one value. However, any number of values ​​can now be stored in an array, even of different types. For example, a PHP array can contain a string (string/text), an integer and a number with decimal places, and each of these values ​​can be accessed separately.

It may sounds complicated now, so here's a live example for you:

<?php
$weekdays = array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
echo $weekdays[1];
?>

A PHP array is typically assigned a variable name, here $weekdays, but the assignment of the data is not merely done by the equals sign, but then comes the command: array();.
In this command now the different values ​​are stored in the weekdays variable.

Accessing such a value is also relatively simple:

<?php 
 echo  $weekdays[1] ;       
 ?> 

Output: Monday

First, let's say the variable name (weekdays) and then the element or value we want to access. An array has ordered number to store values ​​and starts counting at 0. So with weekdays [0]; we would get the value Sunday, Monday has the number (or index) 1 and so on.

Define associative arrays

For large arrays, it will eventually be awkward to know which number/index belongs to which value, so there are associative arrays. This means that you can assign a key for the value; this can be a different string, for example. The assignation is done by =>

<?php
$weekdays = array ("so" => "Sunday", "mo" => "Monday", "di" => "Tuesday", "mi" => "Wednesday", "do" => " Thursday "," fr "=>" Friday "," sa "=>" Saturday ");
echo $weekdays ["mo"];
?>

Here we are using weekdays variable to store arrays. The so key was assigned to the value Sunday, the key mo to the value Monday and so on.

The advantage is that you can now more conveniently access the array:

echo  $weekdays["mo"];

Output: Monday

Instead of specifying the number/index of the element, you just need to enter the key of the element, so for Sunday, mo for Monday and sa for Saturday.

Of course you can also change values ​​in an array afterwards:

<?php
$weekdays = array ("so" => "Sunday", "mo" => "Monday", "di" => "Tuesday", "mi" => "Wednesday", "do" => " Thursday "," fr "=>" Friday "," sa "=>" Saturday ");
$weekdays["mo"] = "Monday";
echo $weekdays["mo"];
?>

Output: Monday

Add more values ​​to an array

You can easily add more values ​​to an array. This is done by using [] after the array name:

<?php
$employee = array ("Bob", "Peter");
$employee [] = "Lisa";
echo $employee [2];
?>

Output: Lisa

$employee [] automatically creates a new item in our array and assigns it the value Lisa.

This can also be applied to an empty arrays:

<?php
$employee = array();
$employee [] = "Bob";
$employee [] = "Peter";
$employee [] = "Lisa";
echo $employee[0];
?>

Here an empty array is created first, and then the expected array values are added. How many elements you want to add to the array is up to you.

This works similarly with associative PHP arrays, but we need to specify the new key:

<?php
$employee = array("Bob" => "Bob Moler", "Peter" => "Peter Solder");
$employee["Lisa"] = "Lisa Mules";
echo $employee["Lisa"];
?>

Output: Lisa Mules

If the key Lisa is already taken, then no new entry is created, but the existing entry is overwritten.

Convert arrays to strings

By using implode($separator, $array) function, Here you can connect the elements of an array to a string. You can use the variable $separator to specify which connector should appear between the elements. This feature is very useful to output, e.g. formatted lists. Especially with other array functions, e.g., for sorting the array.

<?php
$names = array ("Paul", "Max", "Hans");
echo "Separated names by comma: <br>";
$namesStr = implode (",", $names);
echo $nameStr; echo "<br> <br>";
echo "One name per line: <br>";
echo implode("<br>", $names);
?>

Convert strings to arrays

Opposite to the implode() function, by using explode ($separator, $text), a string can be converted into an array. Here, the text string is separated on all occurrences of $separators.

<?php
$text = "Paul, Max, Hannes";
$names = explode (",", $text); // converting the string into an array echo "<pre>"; var_dump ($name);
echo "</ pre>"; // Formatted output of the array // Replace the 1st person with a new name
$name[1] = "Lisa"; // turn the array back into a string
$text = implode (",", $names);
echo $text;
?>

Define multidimensional arrays

In an array, you can save another array and another more arrays inside the array, etc. Such arrays are called multidimensional arrays. The dimension indicates how deep this nesting is. A normal array would be a 1-dimensional array, and if another array is now stored in the array, this is a 2-dimensional array.

Here is an example:

<?php
$employee = array (array ("Kader", "Zabel"), array ("Arnold", "Maya"), array ("Willi", "Brand"));
// output data
echo "First name:". $employee [0][0];
echo " Last Name:". $employee [0][1];
?>

Output: First name: Kader Last name: Zabel

As you can see, you are now specifying not just one index, but two indexes. The first index indicates which employee we want from the list, and the second index if we're going to print the first name or last name.

Normal arrays and associative arrays can be easily combined:

<?php
$employee = array();
$employee [] = array ("firstname" => "Kader", "lastname" => "Zabel");
$employee [] = array ("firstname" => "Arnie", "lastname" => "Meier");
$employee [] = array ("firstname" => "Willi", "lastname" => "Brand");
// output data
echo "First name:". $employee [0]["firstname"];
echo " Last Name:". $employee [0]["lastname"];
?>

Since we now store an associative array (i.e. one with a key) in a normal array, we must also specify the key for first/last name as the second value.

Of course, this also works with even more dimensions, for example:

<?php
$employee = array();
$employee["Kader"]["firstname"] = "Kader";
$employee["Kader"]["lastname"] = "Zabel";
$employee["Kader"]["children"] [] = "Kader-Junior";
$employee["Kader"]["children"] [] = "child2";
// output data
echo "First Name:". $employee ["Kader"]["firstname"];
echo " Last Name:". $employee ["Kader"]["lastname"];
echo "<br> He has "; echo count($employee ["Kader"]["children"]). " children";
// output of child1:
// $employee ["Kader"]["children"] [0];
echo "<br> Children: <br>";
foreach ($employee["Kader"]["children"] as $name) {
echo $name. " <br />";
}
?>

This is a bit harder to understand, but once you know it, there should not be any more questions about arrays.

So first we have our array with the employee Klaus. We use an associative array this time.

For Klaus, the first name and the last name have now been saved. Under the Children key, we'll add another array, with each element of that array containing a child's name. This array with the children's names, we can usually spend by foreach.

Browse arrays

Using the function in_array ($search, $array), we can check if a value exists in an array .:

<?php
$employee = array ("Bob", "Peter", "Lisa");
$name = "Bob";
if (in_array ($name, $employee)) {
echo "The name $name is contained in the array";
}
?>

In the example above, it checks to see if Bob is in the employee array, if so, returns true and the if statement executes accordingly.

For associative arrays you can use array_key_exists ($key, $array) to check if a key exists in the array:

<?php
$employee = array("Bob" => "Builder", "Klaus" => "Pattern");
$key = "Bob";
if (array_key_exists ($key, $employee)) {
echo "The element $key has the value:". $employee [$key];
} else {
echo "The array has no key $ key";
}
?>

Iterate over the elements of an array

By using the function count($array), the number of elements of an array can be determined. Thus, a corresponding for loop can be used to go through all the elements. Alternatively, the foreach loop can also be used. For associative arrays, one usually resorts to a foreach loop because there are no ascending indices left.

<?php
$names = array("Kader", "Anna", "Dator");
echo " Iterating through the array using the for loop:<br>";
for ($i = 0; $i <count ($names); $i ++) {
echo $names [$i]. ","; }
echo "<br> Iterating through the array using the foreach loop:<br>";
foreach ($names as $name) {
echo $name. ",";
}
?>

In addition, the index of arrays can also be displayed via foreach and using the => notation. We are going to modify the above example looks like below:

<?php
$names = array("Kader", "Anna", "Dator");
echo "Iterating through the array using the foreach loop:<br>";
foreach ($names as $index => $name) {
echo "Index $index: $name, ";
}
?>

Delete duplicate entries in the array

By using array_unique() function, we can quickly and easily delete all duplicate values ​​of an array. See example:

<?php
$operatingsystem [] = "Windows" ;
$operatingsystem [] = "Linux" ;
$operatingsystem [] = "Solaris" ;
$operatingsystem [] = "Android" ;
$operatingsystem [] = "Linux" ;
$bs = array_unique ( $operatingsystem );
echo "<pre>" ;
print_r ( $bs );
?>

Sorting arrays

Arrays can be sorted using the sort () function to sort in ascending order (a to z). Using the function rsort () you can sort an array in descending order (z to a).

<?php
$names = array ("Klaus", "Dieter", "Anna", "Melissa", "Arne");
sort ($names);
echo implode(",", $names);
?>

In the above script is the output: Anna, Dieter, Klaus, Melissa, arne.

It may come as a surprise that Arne is at the bottom of the array. This occurs through the lowercase letters, these are sorted after the uppercase letters. Do you want that arne sorted after Anna, you have the function natcasesort($names) use.

Useful array functions

There are some useful array functions for working with arrays, Below is a list of the most important:

  • array_key_exists ($key, $array) - Checks if the key $key exists in the $array.
  • count($array) - Returns the number of elements in the array.
  • in_array ($search_value, $array) - Checks if $value value exists in $array.
  • sort ($array) - Sorting an array in ascending order, from the smallest to the largest value (A -> Z).
  • rsort ($array) - Sorts an array in descending order, from largest to smallest value (Z -> A).
  • shuffle($array) - randomly mix the elements of the array.
  • array_count_values - Counts all the values ​​of an array
  • array_diff - Compares arrays and returns the differences (in new array)
  • min() - Returns the element with the lowest value
  • max() - Returns the element with the highest value
  • array_merge() - Merge two or more arrays
  • range() - Creates an array with the lower and upper ranges (e.g., lottery numbers 1 to 36)
«