Array Explanation for app.codility.com/programmers in PHP
Category of Article : Technology | Computers and Software | Algorithm
By: Chrysanthus Date Published: 2 May 2025
An array is a list structure that can be used to store many items in one place.
List Example
Imagine that you are a proprietor of a small company, and you have 10 employees. In your PHP program, you can have their first names in an array. Each list item here is a first name. Let the list be: John, Mary, Peter, Augustine, Angela, Susan, Martin, Grace, Paul, Simon. These items can be placed in a special PHP object called an array. An array item is called an element.
Creating an Array
There are two ways of creating an array: you either use the constructor, Array() or you use the short arraay syntax, [].
Creation with Constructor
The syntax to create an empty array with the constructor is as follows:
arr = Array();
The syntax to create an empty array with the short array syntax is as follows:
arr = [];
Adding Elements to an Array.
Initial elements can be added to an array as follows, using the independent array_push() function:
<?php
$arr1 = Array();
array_push($arr1, 'John', 'Mary', 'Peter', 'Augustine', 'Angela');
print_r($arr1);
$arr2 = [];
array_push($arr2, 'Susan', 'Martin', 'Grace', 'Paul', 'Simon');
print_r($arr2);
?>
The first argument to the independent array_push() function is the name of the array. The output for the two arrays is:
Array
(
[0] => John
[1] => Mary
[2] => Peter
[3] => Augustine
[4] => Angela
)
Array
(
[0] => Susan
[1] => Martin
[2] => Grace
[3] => Paul
[4] => Simon
)
The print_r() function prints out the array.
Creating an Array and Initialization at the Same Time
The following script creates two different arrays with the two different syntaxes, with initialization at the same time:
<?php
$arr1 = Array('John', 'Mary', 'Peter', 'Augustine', 'Angela');
print_r($arr1);
$arr2 = ['Susan', 'Martin', 'Grace', 'Paul', 'Simon'];
print_r($arr2);
?>
The output is the same as above. Note that the array name is not in the parentheses or in the square brackets.
Array Indices
The value of an array can be addressed using integers (whole numbers). These integers are called indices or indexes (singular is index). The syntax to access an array value (element) is:
arrayObject[index]
where arrayObject is the array identifier and index is an integer beginning from zero. Counting of array elements (values) begin from zero, not 1. You count as follows: 0, 1, 2, 3, 4, etc.
Reading Array Values
To read the value at position 3 of an array, you have to use the index, 2, since index counting begins from zero, not 1. You always have to subtract the value of 1 from the position to get the index. So, to read the value of an array at position, 3 you would type something like:
$valRead = $arr[2];
Here, $arr is the array identifier and 2 is the index. Note the use of the square brackets. The value is read and assigned to the identifier, $valRead, which is a name of your choice. You can also type the integer (2 for example), in quotes.
Giving Values to an Array
You can give values to an array during creation or you can give the values using the bracket notation (square brackets). The following statement shows how you would create an array of the above list, using the constructor and giving values at the same time:
$arr = Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");
Here, $arr is the identifier of the array; it is a name of your choice. It can also be done with the array initializer (using square brackets) as follows:
$arr = ["John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"];
The other way of giving value is by the square bracket notation. For this you create an empty array first. Then you assign values beginning from index zero. The following code segment illustrates this:
$arr = Array();
$arr[0] = "John";
$arr[1] = "Mary";
$arr[2] = "Peter";
$arr[3] = "Angela";
The index number is always 1 less than the position number. The empty array can also be created as follows, with empty array initializer (empty square brackets):
$arr = [];
$arr[0] = "John";
$arr[1] = "Mary";
$arr[2] = "Peter";
$arr[3] = "Angela";
Changing the Value of an Array Element
To change the value of an array element, use the bracket notation. If you want to change the value at position 2 of the $arr array above, from "Mary" to "Beyonce", you would type a new line in the script as follows:
arr[1] = "Beyonce";
It is that simple, just reassign a new value below the created array in the script.
Displaying Array Content
You can display the array values one-by-one, or you can display them all in one sweep. To display an array value, you can type something like,
echo $arr[2];
for index 2, position 3;
If the value is assign to an identifier as in,
$valRead = arr[2];
then you can use the identifier as the argument for the echo predefined function.
To display all the values of the array, use the predefined print_array function, print_r() - see above.
Iterating over an Array
The do-while-loop
The following script shows a do-while-loop in PHP :
<?php
$arr = ["bread", "butter", "cheese"]; //array of strings
$i = 0;
do {
echo $arr[$i] . "\n";
$i = $i + 1; //increment: add 1
} while ($i < 3);
?>
The output consists of each of the array elements, beginning from the first, then second and then third.
The do-while-loop has a block, delimited by curly brackets (braces). The "do" reserved word is in front of this block. The loop uses a variable, $i that is incremented for each pass, through the block.
The statements in the block are executed over and over, in the order typed. The while-condition is that, the block should stop executing, when the value of $i is just below 3, that is 2. The first statement in the block prints out an array value. The second statement increments $i (adds 1). The block is executed 3 times; when $i is 0; $i is 1; and $i is 2. $i was initialized to 1, in front of the do-while-loop.
With the do-while-loop, the block is executed before the while-condition is checked. Note that the do-while-loop construct ends with a semicolon, just after the while-condition "(i<3)".
The While-Loop
The while-loop is similar to the do-while-loop. With the while-loop, the while-condition is checked before the loop body (block) is executed, for each iteration. With the do-while-loop above, the body is executed first, before the while-condition is checked, for each iteration. The following while-loop code segment would replace the above do-while-loop code segment (would do the same thing):
$arr = ["bread", "butter", "cheese"]; //array of strings
$i = 0;
while ($i < 3) {
echo $arr[$i] . "\n";
$i = $i + 1; //increment: add 1
};
Note that the while-loop construct does not end with a semicolon after, '}'. Also note the alternative increment statement, "$i += 1;", which is the same as "$i = $i + 1;"
The for-Loop
The while-loop has a difference with the do-while-loop. The for-loop is another way of coding the while-loop. The above while-loop code segment would be coded with the for-loop as follows:
<?php
$arr = ["bread", "butter", "cheese"]; //array of strings
for ($i = 0; $i < 3; $i++) {
echo $arr[$i] . "\n";
}
?>
The for-loop begins with the reserved word, "for" with all letters in lowercase. Then there is the parentheses. In the parentheses, there are three statements, with the last one not ending with a semicolon. The last statement is the increment statement, which has been transferred from the body of the while-loop, to this position. The middle statement is the while-condition. The first statement is the initialization of i to 0; it is no longer outside the construct. There is now only one statement in the body of this loop (for-loop). The output here, is the same as in the previous cases.
Other Script Examples
In the following script, an array for the list above is created by calling the array constructor as a function, with all the values given as argument. One of the values in the array is displayed.
<?php
$arr = Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");
$indxIdent = $arr[4];
echo $indxIdent . "\n";
?>
The output is "Angela" of index 4, position 5. Always subtract 1 from the position to have the index. You should try the above code.
In the following script, an empty array is created with empty square brackets, without giving the values. Some values at certain positions are then given. The whole array is then displayed.
<?php
$empArr = [];
$empArr[0] = "John";
$empArr[2] = "Peter";
$empArr[4] = "Angela";
$empArr[6] = "Martin";
print_r($empArr);
?>
The output is:
Array
(
[0] => John
[2] => Peter
[4] => Angela
[6] => Martin
)
The skipped index elements are skipped at the output:
Note: you can type the index within single or double quotes, so
$empArr["2"] = "Peter";
is alright.
Adding Values to an Array
To add a value you can use the bracket notation. If you make a mistake and use an index that is already in the array, you would end up changing the value of that index. For example, if in the above array, where there are 10 elements, and you add a value, using index 4, you will change the value of index 4 which is "Angela" at the moment. If for an element whose value does not exist, you give the element a new value, you will have a new value for that element.
To add an element (value) successfully, you have to use an index that is higher than that of the array highest index. For the above array, since there are 10 elements, it means that highest current index is 9. With that you can add an element with index, 10, or 11, or 12, or 13, etc. If you add an element with an index that is higher than the current highest index plus 1 (e.g. 18 for the above list), you end up with the added element and elements with values that do not exist, whose indices are between that which you have just added and the previous highest index.
In the following code of initially 3 elements, an element (value) has been added at index 12. The resulting whole array is displayed.
<?php
$empArr = ['John', 'Mary', 'Peter'];
$empArr[12] = "Victoria";
print_r($empArr);
?>
The output is:
Array
(
[0] => John
[1] => Mary
[2] => Peter
[12] => Victoria
)
Array of Initial Length and Default Value
To achieve this, use the array_fill() predefined function to create the array. The following program illustrates this:
<?php
$arr = array_fill(0, 3, 'default_value');
print_r($arr);
?>
The output is:
Array
(
[0] => default_value
[1] => default_value
[2] => default_value
)
The first argument in the array_fill() function is the start index. The second argument is the number of elements. The third argument is the default value for all the elements.
Length of an Array
To know the length of an array, use the predefined count() function, as in the following script;
<?php
$cutlery = Array("spoon", "knife", "fork");
$length = count($cutlery);
echo $length . "\n";
?>
The output is 3.
In the code the expression, "cutlery.length" obtains the length of the object, cutlery and assigns it to the identifier, len.
Value as Number
When the value of an array element is a number, type the number without quotes. The following example illustrates this:
$ages = Array(12, 15.5, 16);
Array Literal
The array literal is the array initializer. Thus:
$arr = [];
or
$ages = [12, 15.5, 16];
Adding and Removing Elements in PHP
The array_shift() Predefined Function
This function removes the first element of the array and returns the element, shortening the array by one element. Re-indexing takes place, i.e. index 1 becomes index 0, index 2 becomes index 1, etc. The argument to the function is the name of the array. Example:
<?php
$ages = Array(12, 15.5, 16);
$shifted = array_shift($ages);
echo $shifted . "\n";
print_r($ages);
?>
The output is:
12
Array
(
[0] => 15.5
[1] => 16
)
If the array is empty, the array_shift() function returns null.
The array_unshift() Predefined Function
This function prepends one or more elements to the front of the array. The elements in the incoming argument list are fitted to appear in the same order they were in the input list (first in input list will become first in new list). The length of the resulting array increases. Re-indexing takes place, i.e. index 0 may become index 1, index 1 may become index 2, etc. Example:
<?php
$tools = ["Hammer", "screw driver"];
array_unshift($tools, "saw", "pincer");
print_r($tools);
?>
The first argument to the array_unshift() function is the name of the array. The rest of the arguments are elements to be un-shifted. The output is:
Array ( [0] => saw [1] => pincer [2] => Hammer [3] => screw driver )The array_pop() Predefined Function
This function removes the last element of an array and returns the value, shortening the array by one element. If the array is empty, the function returns null. Example:
<?php
$arr = Array("Martin", "Grace", "Paul", "Simon");
$val = array_pop($arr);
echo $val . "\n";
print_r($arr);
?>
The argument for the array_pop() function, is the name of the array. The output is:
Simon
Array
(
[0] => Martin
[1] => Grace
[2] => Paul
)
The array_push() Predefined Function
This function adds one or more elements to the end of the array. The length of the array increases by the number of elements added. Example:
<?php
$tools = ["saw", "pincer"];
array_push($tools, "Hammer", "screw driver");
print_r($tools);
?>
The first argument to the function, is the name of the array. The rest of the arguments are the new elements. The output is:
Array
(
[0] => saw
[1] => pincer
[2] => Hammer
[3] => screw driver
)
The array_slice() Predefined Function
This function reads and returns a sequence of elements from the original array. The return entity is an array, the slice. The original array remains unchanged. Read and test the following code:
<?php
$arr = Array("AA", "BB", "CC", "DD", "EE", "FF", "GG");
$ret = array_slice($arr, 2, 3);
print_r($ret);
print_r($arr);
?>
Note that the original array remains unchanged. The syntax of the slice() method is:
The first argument to the function is the name of the original array. The second argument is the start index (index counting begins from 0). The third argument is optional and it is the length or number of elements to be sliced, beginning from the start index. If the third argument is omitted, the rest of the array is sliced. The output is:
Array
(
[0] => CC
[1] => DD
[2] => EE
)
Array
(
[0] => AA
[1] => BB
[2] => CC
[3] => DD
[4] => EE
[5] => FF
[6] => GG
)
The array_splice() Predefined Function
The array_slice() function only copies the sequence of elements and leaves the original array unchanged. However, the splice() function removes the sequence of elements and can replace the sequence with a longer or shorter new sequence. After removing the sequence, the function can even replace it with nothing. The syntax of the function is:
array_splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array
where &$array is the name of the original array. $offset is the optional start index at which the function starts removing elements. $length (optional) is the number of elements to be removed, beginning from the start index. The elements for replacement, if any, are typed after that, as an array.
The function returns an array consisting of the removed elements.
Read and test the following code:
<?php
$arr = Array("AA", "BB", "CC", "DD", "EE", "FF", "GG");
$ret = array_splice($arr, 2, 3, ["PP", "QQ"]);
print_r($ret);
print_r($arr);
?>
The output is:
Array
(
[0] => CC
[1] => DD
[2] => EE
)
Array
(
[0] => AA
[1] => BB
[2] => PP
[3] => QQ
[4] => FF
[5] => GG
)
If the length argument is to be omitted, it has to be replaced with null, as in the following statement:
$ret = array_splice($arr, 2, null, ["PP", "QQ"]);
PHP Array Data Predefined Functions
The sort() Predefined Function
This sorts the original array. Read and test the following code:
<?php
$arr = ["pear", "orange", "strawberry", "lime", "lemon", "avocado", "guava", "banana"];
sort($arr);
for ($i=0; $i < count($arr); $i++)
echo $arr[$i] . ', ';
echo "\n";
?>
The first argument to the function is the name of the array. The output is:
avocado, banana, guava, lemon, lime, orange, pear, strawberry
The array_reverse() Predefined Function
This function returns the reversed form of the original array. The original array remains unchanged. Read and test the following code:
<?php
$arr = ["avocado", "banana", "guava", "lemon", "lime", "orange", "pear", "strawberry"];
$ret = array_reverse($arr);
for ($i=0; $i < count($arr); $i++)
echo $arr[$i] . ', ';
echo "\n";
for ($i=0; $i < count($ret); $i++)
echo $ret[$i] . ', ';
echo "\n";
?>
The first argument of the function is the name of the original array. The output is:
avocado, banana, guava, lemon, lime, orange, pear, strawberry,
strawberry, pear, orange, lime, lemon, guava, banana, avocado,
The first argument to the function is the name of the array.
Converting an Array into a String
The implode() predefined function can be used to join all the elements of an array, into a string. There has to be a separator like the comma (followed by space), to separate the elements in the string. In simple terms, the syntax is:
$string = implode("separator", $array_name);
Read and test the following code, where the separator is the single space:
<?php
$arr = ["United", "Nations", "Educational", "Scientific", "and", "Cultural", "Organization"];
$str = implode(' ', $arr);
echo $str . "\n";
?>
The output is:
United Nations Educational Scientific and Cultural Organization
The rest of the 17 lessons, with explanation of lessons, explanation of tasks, and explanation of solutions, can be found at (click): Explanations in PHP for the 17 Algorithm Lessons at https://app.codility.com/programmers with Problems and Solutions
Related Links
Basics of PHP with Security ConsiderationsWhite Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links