How to shuffle an array in Lua

Arrays

February 10, 2020
  1. Home
  2. »
  3. PHP tutorial
  4. »
  5. Arrays

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

See also the following three articles on iterating over the elements of an array, foreach loop and sorting arrays.

Table of Contents

Define arrays

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

It all sounds pretty complicated, but it's very simple, so here's an example:

<?php $wochentage = array("Sonntag","Montag","Dienstag", "Mittwoch","Donnerstag","Freitag","Samstag"); echo $wochentage[1]; ?>

One PHP array a variable name is assigned as normal, here weekdays, however, the data is not assigned simply by the equal sign, but followed by the command: array ();.
The various values ​​are now saved in this command, in our case the days of the week written out.

Accessing such a value is also relatively simple:

Issue: Monday

We first give the variable name again (weekdays) and then the element or value that we want to access.
An array has numbered the contained values ​​and starts with 0 to count on.
So with $ days of the week [0]; we would value Sunday receive, Monday has the number (or the index) 1 and so on.

Define associative arrays

With large arrays it becomes awkward to know which number / index belongs to which value at some point, that's why there is associative arrays. This means that you can assign a key (also called a key) for a value, this can e.g. be a different character string. The assignment is made by =>

<?php $wochentage = array( "so" => "Sonntag", "mo" => "Montag", "di" => "Dienstag", "mi" => "Mittwoch", "do" => "Donnerstag", "fr" => "Freitag", "sa" => "Samstag"); echo $wochentage["mo"]; ?>

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

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

Issue: Monday

Instead of specifying the number / index of the element, you enter the key for the element here, i.e. so For Sunday, mo For Monday and sa For Saturday.

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

<?php $wochentage = array( "so" => "Sonntag", "mo" => "Montag", "di" => "Dienstag", "mi" => "Mittwoch", "do" => "Donnerstag", "fr" => "Freitag", "sa" => "Samstag"); $wochentage["mo"] = "Monday"; echo $wochentage["mo"]; ?>

Edition: Monday

Add more values ​​to an array

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

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

Edition: Lisa

$ Employee [] automatically creates a new element in our array, and that becomes the value Lisa assigned.

This can also be applied to empty arrays:

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

Here an empty array is first created 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 have to include the new key:

<?php $mitarbeiter = array( "Bob" => "Bob Meier", "Peter" => "Peter Schröder"); $mitarbeiter["Lisa"] = "Lisa Müller"; echo $mitarbeiter["Lisa"]; ?>

Edition: Lisa Müller

Should be the keyLisa are already assigned, then no new entry is created, but the existing entry is overwritten.

Convert arrays to strings

A very useful feature is implode ($ separator, $ array). With this you can connect the elements of an array to a string. Using the variable $ separator you can specify which connecting element should appear between the elements. This function is very useful, e.g. to output formatted lists. This is particularly useful with other array functions, e.g. for sorting the array.

 

"; $ namenStr = implode (",", $ namen); echo $ namenStr; echo "

"; echo "One name per line: "; echo implode (" ", $ names);Convert strings to arrays In contrast to implode ().

can be done using

 

explode ($ separator, $ text)

convert a text (string) into an array. Here the text is applied to all occurrences of $ separatorCut

"; var_dump ($ names); echo ""; // Formatted output of the array // Replace the 1st person with a new name $ names [1] = "Lisa"; // convert the array back to a string $ text = implode (",", $ names); echo $ text;

<?php $mitarbeiter = array( array("Klaus", "Zabel"), array("Arnie", "Meier"), array("Willi", "Brand") ); //Daten ausgeben echo "Vorname: ".$mitarbeiter[0][0]; echo " Nachname: ".$mitarbeiter[0][1]; ?>

Define multidimensional arrays

Another array can be stored in an array. And in this array another array, etc. Such arrays are then called

multidimensional arrays

<?php $mitarbeiter = array(); $mitarbeiter[] = array("Vorname"=>"Klaus", "Nachname"=>"Zabel"); $mitarbeiter[] = array("Vorname"=>"Arnie", "Nachname"=>"Meier"); $mitarbeiter[] = array("Vorname"=>"Willi", "Nachname"=>"Brand"); //Daten ausgeben echo "Vorname: ".$mitarbeiter[0]["Vorname"]; echo " Nachname: ".$mitarbeiter[0]["Nachname"]; ?>

. The dimension indicates how deep this nesting goes. A normal array would be a 1-dimensional array, if another array is now stored in the array, this is a 2-dimensional array.

Here is an example:

<?php $mitarbeiter = array(); $mitarbeiter["Klaus"]["Vorname"] = "Klaus"; $mitarbeiter["Klaus"]["Nachname"] = "Zabel"; $mitarbeiter["Klaus"]["Kinder"][] = "Klaus-Junior"; $mitarbeiter["Klaus"]["Kinder"][] = "Kind2"; //Daten ausgeben echo "Vorname: ".$mitarbeiter["Klaus"]["Vorname"]; echo " Nachname: ".$mitarbeiter["Klaus"]["Nachname"]; echo "<br> Er hat "; echo count($mitarbeiter["Klaus"]["Kinder"])." Kinder"; //Ausgabe von Kind1: //$mitarbeiter["Klaus"]["Kinder"][0]; echo "<br> Kinder: <br>"; foreach($mitarbeiter["Klaus"]["Kinder"] AS $name) { echo $name."<br>"; } ?>

Edition: First name: Klaus Last name: Zabel

As we can see, you now give not just one index, but two. The first index indicates which employee we would like to have from the list, and the second index whether we would like to output the first name or the last name. Normal arrays and associative arrays can be easily combined with each other:Since we are now storing 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 more dimensions, e.g. like this: This is a little harder to understand, but once you understand it there shouldn't be any more questions about arrays.So first we have our array again with the employee Klaus. This time we use an associative array.

For

Klaus the first name and last name have now been saved. Under the keychildren

<?php $mitarbeiter = array("Bob","Peter","Lisa"); $name = "Bob"; if(in_array($name,$mitarbeiter)) { echo "Der Name $name ist in dem Array enthalten"; } ?>

let's now add another array, each element of this array containing the name of one of its children. We can output this array with the child names via foreach as normal. Browse arraysBy means of the function

in_array ($ search, $ array) you can check whether a value is available in an array .:The above example checks whether

<?php $mitarbeiter = array("Bob" => "Baumeister", "Klaus" => "Muster"); $key = "Bob"; if(array_key_exists($key, $mitarbeiter)) { echo "Das Element $key hat den Wert: ".$mitarbeiter[$key]; } else { echo "Das Array hat keinen Schlüssel $key"; } ?>

bob

is present in the employee array, if so, the function returns true and the if statement is executed accordingly.

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

<?php $namen = array("Klaus", "Anna", "Dieter"); echo "<br> Durchlaufen des Arrays mittels for-Schleife: "; for($i=0; $i<count($namen); $i++) { echo $namen[$i].", "; } echo "<br> Durchlaufen des Arrays mittels foreach-Schleife: "; foreach($namen AS $name) { echo $name.", "; } ?>

Iterate over the elements of an array

See article Iterating over the elements of an array.

By means of the function count ($ array) the number of elements in an array can be determined. A corresponding for loop can thus be used to run through all elements. Alternatively, the foreach loop can also be used. A foreach loop is usually used for associative arrays, since there no longer exist any ascending indexes. Sort arraysSee article Sort Arrays.

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

Arrays can be created using the sort ()

sort in ascending order (a to z). By means of the function rsort () an array can be sorted in descending order (z after a). In the script above the output is:Anna, Dieter, Klaus, Melissa, arne. It may surprise you that arne is at the end of the array. This is due to the lower case letters, these are only sorted according to the upper case letters. Do you want thatarne

to

Anna

  • is sorted, you have to use the functionnatcasesort ($ names)
  • use.Useful array functions
  • There are a number of useful array functions for working with arrays. In the following you will find a list of the most important:array_key_exists ($ key, $ array)
  • - Checks whether the key $ key exists in the $ array.count ($ array)
  • - Returns the number of elements in the array.in_array ($ search-value, $ array)
  • - Checks whether the value $ search value exists in the $ array.sort ($ array)
- Sorts an array in ascending order, from smallest to largest value (A -> Z).