Czech version
logolink

< Back to the list of lessons

Práce s polem

PHPContent of the lesson:

  • Introduction to Arrays
  • Indexing of an Array
  • Other Array Types
  • Browsing an Array
  • Useful Functions
  • Tips and Tricks
  • Diacritic Removal
  • Homework I and II

Introduction to Arrays

There is a special data type named array in PHP next to the basic data types (integers, floats, booleans, strings). You can imagine an array as a row of variables (usually variables of the same type but it is not required).

We are going to explain an array using an example. We have a queue for lunch which consists of several people and more people are coming. We do not know the number of people in the queue because new people are still coming but we need to store several information about these people - for example name and their choice of meal. We need a data type which can hold as many information as we need without the need to know the exact number of elements - we need an array.

Arrays are used for all lists, they can simulate dictionaries, store collections of elements and many other things so they are a very useful tool.

Every array has its items and every item has its index (key) and value. The following source code creates an array fronta and fills it with the names of people inside the queue.

$fronta[1]="Petr";
$fronta[2]="Pavel";
$fronta[3]="Marie";
$fronta[4]="Eva";
$fronta[5]="David";
Jednoduché pole

Indexing of an Array

We stored 5 names inside the array, so the first item with index 1 stores the value Petr and so on. We can get the same result using this much shorter source code:

$fronta=Array(1=>"Petr", "Pavel", "Marie", "Eva", "David");

This command starts with assigning the value Petr to the first index because every array is indexed from 0 in PHP (pay attention because arrays in Pascal are indexed from 1) so we have to define that we want the array to be indexed from another number.

The first set of commands can be replaced by this set because there is no need to specify the following indexes after the first one - PHP will increase them automatically.

$fronta[1]="Petr";
$fronta[]="Pavel";
$fronta[]="Marie";
$fronta[]="Eva";
$fronta[]="David";

You also do not have to assign the values gradually, you could continue assigning the item with index 1000 - the array would be enlarged to be able to store 1000 items and your value would be stored. The items between would probably contain useless data.

Indexes can be also replaced by texts which can be useful in several situations (such an array is called an associative array; a standard array is called an indexed array). A good example is an array with configuration:

$config[5] = 15;
$config["max_users"] = 15;

You see that the first line does not tell anything about the setting but the second one tells us that we set the maximum number of users to 15. An associative array would also be useful for a file with web translations of several languages for example.

Other Array Types

Arrays can also be expanded to more dimensions - 2D arrays or 3D arrays for example. However, using more dimensions rapidly increases the requirements for system resources (mostly the RAM memory).

An example using a 2D array:

$pole[0][1] = "some text";

A typical example would be the chess game or gomoku. To browse such an array you have to use two nested for cycles.

Browsing an Array

An array can be browsed using three basic types of algorithms. The array with a fictive queue will be used for these examples.

For cycle

for ($i=1; $i<6; $i++){
  echo $fronta [$i];
}

The cycle simply begins reading the first index inside the array and it writes the first 5 records. In every pass the current value of the item located at the i index in our array is written.

Foreach cycle

foreach($fronta as $stravnik){
  echo $stravnik;
}

The foreach cycle is similar to the for cycle but you do not have to enter any conditions, all items are written automatically. The syntax is easy - you have to enter the name of an array at first, then the keyword as and finally a variable to store the current value of the item to be able to work with it.

Current, Key, Next and more

Reset($fronta);
while (Current($fronta)){
  echo “Index: ”. Key($fronta).”\n”;
  echo “Hodnota: ”.Current($fronta).”\n”;
  Next($fronta);
}

You can also use more commands like Prev(array), Each(array) and End(array). This way is more difficult and has several limitations so you can learn it yourself if you want.

Useful Functions

PHP offers a large collection of functions ready to help you when working with arrays; some of them are explained here.

count(array)

The function returns the number of items in the array. You can use it for a condition inside the for cycle.

array_walk(array, function)

The function walks through the entire array and applies the selected function (from the second parameter) on every item of the array.

function radka ($string) {
  echo "$string\n";
}
$znamka = array ("výborný", "chvalitebný", "dobrý", "dostatečný", "nedostatečný");
array_walk ($znamka, radka);

At first a function to write a text from parameter is defined, then we define an array of notes and finally we let every note to be written using the radka function on each item.

print_r(array)

The function simply writes the content of the array inside a browser. This is a very useful function for debugging.

in_array(text, array)

The function checks whether the text (you can enter a text or a variable containing text) is stored inside the array. It returns true if the text was found or false if it was not.

shuffle(array)

The function shuffles the items inside the array randomly. This function can be used for galleries or slideshows to change the starting photos and make the page more interesting.

range(min, max)

This function returns an array where items with values from min to max are stored.

$cisla = range(1, 100);

sort(array)

The function sorts the array alphabetically but Czech characters are usually not supported so you should not use this function to sort Czech words (depends on the settings of the server but usually the characters with diacritic are sorted to the end).

Wrong results using the sort function
kočka
pes
zebra
člověk

There are many other functions for sorting the array, you can learn about them in internet: asort, rsort, arsort, ksort, usort, uasort, uksort.

list

This command is used to divide an array into variables. You have to know the number of items inside the array to be able to define enough variables. You can use this function to divide results from a database into variables. The variables do not have to be defined before this command.

list($jmeno, $prijmeni, $email, $pozice) = $zamestnanec;
list($id, $nazev, $cena) = $vyrobek;

explode(delimiter, text)

This function can divide a text in areas where it finds the specified delimiter (character) and the items will be saved into an array. The first parameter is the delimiter, the second one is the text (can be inserted as a plain text or as a string variable).

$input = "Honza,David,Petr,Pavel";
$jmena = explode(",", $input);

The array jmena will be filled with single names, commas will be ignored (comma is the delimiter).

implode(delimiter, array)

This is an opposite function to explode. This function creates a plain text from the array and separates the items using the delimiter. You can set an empty delimiter ("") if you want to. Every item will be used, the function returns the output text.

Tips and Tricks

  • Large or multi-dimensional arrays can require large system resources (mainly the RAM memory) so you should consider using them.
  • You should think about the index-key organization before creating an array to be able to work with the array easily.
  • All items do not have to be the same type but it is recommended not to combine the types if you do not have a serious reason.
  • More than two-dimensional arrays are used very rarely.
  • You should consider using a database instead of combining a large number of arrays inside your project.

Diacritic Removal

We are going to create a function which can replace diacritic characters with normal characters - you can use such an algorithm when saving data to database for example. The replacement could be done by many procedures, 3 of them are explained (the third is the best one).

  1. You can use a switch and case construction and browse the text character by character and test it for the unwanted characters.
  2. Another option is to use the str_replace function which can replace any text but you would have to use this function many times to handle all characters.
  3. The last option is to use the StrTr function which needs 3 arguments. The first argument is the variable with input text, the second argument contains the input characters and the third argument contains the output characters. The function returns an output text.
function BezDK($text)
{
  return StrTr($text,"áčďěéëíľĺňóöřšťůúüýž","acdeeeillnoorstuuuyz");
}

The function searches the input text for each input character and in case it finds one, it is replaced by the corresponding character from the output characters collection (characters with the same order are taken as corresponding).

You should pay attention to write the same number of input characters and output characters and the function is complete.

Homework I

Write 2 functions using the StrTr function. One of them will encrypt a text and the other one will decrypt it. The text will be entered as an argument. Name them encrypt() and decrypt().

The algorithm for encrypting is easy - a mirror encrypting - 'A' character is swapped to 'Z', 'B' to 'Y' and so on. Do not care about Czech characters and non-alphabetic characters such as spaces.

Homework II

The second homework is more difficult. Write a function replaceSecretWords($text) using one text argument which will be returned at the end of the function.

The function should have an array of secret words (create it using any words - for example secret names) and the function should search the input text for any occurrences of the secret words (all of them) and replace the secret words with 'SECRET' headline. Do not forget to leave spaces in the final text.

(Help: use the explode function and nested foreach cycles.)

Additional Texts

Links

Questions and Exercises

  1. Explain the difference between an indexed and an associated array and try to name several examples from practice.
  2. Write a program which will be able to load images from an external text file where every path is saved on a new line. The program should shuffle the images and write them to a browser (try to use more options to write data - for, foreach, ...).
webdesign, xhtml, css, php - Mgr. Michal Mikláš