PHP Lesson 15 – Associative, multidimensional Arrays with Example

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

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

Define PHP Array

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/textt), an integer and a number with decimal places, and each of these values can be accessed separately.

It sounds quite complicated now, but it’s quite simple, so here’s an example:

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

PHP array is normally assigned a variable name, here weekdays, but the assignment of the data is not simply done by the equals sign, but then comes the command: array();,
In this command now the different values are stored, with us the advertised weekdays.

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 numbered the contained values and begins counting at 0.
So with weekdays [0]; would we get the value Sunday, Monday has the number (or index) 1 and so on.

Define associative PHP arrays

With 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 (also called a key) for a value; this can be a different string, for example. The assignment is done by =>

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

echo $weekdays ["mo"];
?>

This is again an array with our names of the weekdays. It was the key to the value Sunday assigned the key mo value Monday and so on.

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

echo $weekdays["mo"];

Output: Monday

Instead of specifying now the number/index of the element, you enter here the key for the element, so for Sundaymo for Monday and sa for Saturday .

Of course, you can also later change values in an array:

<?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 PHP array

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

<?Php
$employee = array("Bob", "Peter");
$employee[] = "Robort";

echo $employee[2];
?>

Output: Robort

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

This can also be applied to empty arrays:

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

echo $employee [0];
?>

Here, an empty array is created first and then the employees are added. How many elements you want to add to an 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 Marley",
   "Peter" => "Peter Akpan");
$employee ["Lisa"] = "Lisa Robort";

echo $employee ["Lisa"];
?>

Output: Lisa Robort

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

Convert PHP arrays to strings

A very useful function is implode ($separator, $array), Here you can connect the elements of an array to a string. You can use the variable $ separators to specify which connection element should appear between the elements. This function is very useful to output eg formatted lists. Especially with other array functions, eg for sorting the array, this is very useful.

<?Php
$names = array ("Paul", "Max", "Hans");

echo "Separate 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

Unlike implode() can be explode($ separator, $text) convert a text (string) into an array. Here, the text in all the occurrences of is $delimiter separated.

<?Php
$text = "Paul, Max, Hannes";
$names = explode (",", $text); // Conversion of 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
$names[1] = "Lisa";

// transform the array back into a string
$text = implode (",", $names);
echo $text;

Define multidimensional arrays

In an array, you can save another array. And in this array another 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 ("Klaus", "Zabel"),
  array ("Arnie", "Meier"),
  array ("Willi", "Brand")
);

// output data
echo "First name:".$employee [0] [0];
echo "Last Name:".$employee [0] [1];
?>

Edition: First name: Klaus Last name: Zabel

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

Normal arrays and associative arrays can be easily combined:

<?Php
$employee = array ();
$employee [] = array ("first name" => "Klaus",
                       "Last Name" => "Zabel");

$employee [] = array ("first name" => "Arnie",
                       "Last Name" => "Meier");

$employee [] = array ("first name" => "Willi",
                       "Last Name" => "Fire");

// output data
echo "first name:".$employee [0] ["first name"];
echo "Last Name:".$employee [0] ["Last Name"];
?>

Since we now store an associative array (ie 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 goes with even more dimensions, eg like this:

<?Php
$employee = array ();
$employee ["Klaus"] ["first name"] = "Klaus";
$coworker ["Klaus"] ["surname"] = "Zabel";
$employee ["Klaus"] ["children"] [] = "Klaus-Junior";
$employee ["Klaus"] ["children"] [] = "child2";

// output data
echo "First name:". $employee ["Klaus"] ["First name"];
echo "Last Name:". $employee ["Klaus"] ["Last Name"];
echo "<br> He has";
echo count ($employee ["Klaus"] ["children"]). "Children";

// output from child1:
// $staff["Klaus"] [ "children"] [0];

echo "<br> Children: <br>";
foreach ($employee ["Klaus"] ["children"] AS $name) {
   echo $name. "<br>";
}
?>

This is a bit harder to understand, but once you understand 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 spend normally by foreach .

Browsing PHP arrays

Using the function in_array ($ search, $ array)  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)  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 PHP array

By means of 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 ("Klaus", "Anna", "Dieter");

echo "<br> iterating through the array using the for loop:";
for ($i = 0; $i < count($names); $i++) {
  echo $name[$i]. ",";
}

echo "<br> iterating through the array using the foreach loop:";
foreach ($name AS $name) {
  echo $name. ",";
}
?>

Sorting PHP arrays

Arrays can be sorted using the sort() function 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($name);
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 comes by the lowercase letters, these are sorted only after the uppercase letters. Do you want that arne sorted after Anna , you have the function natcasesort ($names)  use.

Useful array functions in PHP

There are a number of 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)  – Sorts 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 elements of the array.

About The Author

Related posts

Leave a Reply