PHP provides structured data types that are more commonly called “tables”. What do they do exactly? How do we handle?
We’ll be covering the following topics in this tutorial:
What is a table?
Above all, it is good to clarify that a PHP array and an HTML table are two completely different things. A PHP arrays function is to store and manipulate information while an HTML table used to display data on a screen.
The tables, also referred to as arrays in English, are structured data types for grouping information together. Unlike primitive types (integer, real, float, boolean, character string), the tables can store one or more values at a time (of different types).
When declaring an array, there is no need to specify its size and type of data it will contain. PHP does this automatically. The array are called dynamic. Each new entry recorded in the array, PHP expands its size of 1 element.
PHP also offers two distinct types of array: array in numerical indexes and associative arrays.
Declaring an array
The declaration of an empty array is a variable in the same way, ie with a dollar sign ($) and a name. The format name must follow the same reporting rules as a variable. We will then identify the array by the name we have assigned.
To declare a new array, just use the language construct array (). This function supports optional parameters (separated by commas), the values that one wishes to insert into the array to initialize. If nothing is specified as a parameter, the created array will be empty. Here are 3 examples of declaration and initialization array.
Declaration and initialization array
<?php // Declare an empty array $fruits = array();
// Declare an array indexed numerically
$vegetables = array (‘carrot’, ‘pepper’, ‘Onion’, ‘cabbage’);
// Declare an associative array
$identity = array (
‘firstname’ => ‘Karan’,
‘lastname’ => ‘Johar’,
‘age’ => 19,
‘Student’ => true
);
?>
Explanations:
• The first statement creates an empty array called $fruit.
• The second declares a numerically indexed array of name $vegetables and filled with 4 values.
• Finally the last array created is an associative array of name $identity and couples of composed key => value.
Adding a new entry in a array
To dynamically add a new value at the end of the previous arrays, simply proceed as explained in the following example:
Adding element in an array
<?php // Add a vegetable in spreadsheet numerically indexed $vegetables [] = 'salad';
// Add the size of the person in the associative array
$identity [‘size’] = 180;
?>
Explanations:
• The first statement dynamically adds the ‘salad’ at the end of the array. The array therefore now contains: ‘carrot’, ‘pepper’, ‘Onion’, ‘cabbage’, ‘salad’.
• The second statement dynamically creates a new key pair (‘size’) => value (180) at the end of the array.
In the case of numerically indexed array, it is also possible to add a value to a specific index by doing this:
Adding elements in an array digital keys
<?php // Add vegetables spreadsheet $vegetables [12] = 'Chard'; $vegetables [20] = 'chili';
?>
Explanations:
• PHP dynamically expands the array $vegetables and adds the ‘Chard’ to index 12.
• PHP still dynamically expanding the array $vegetables and adds the ‘chili’ to index 20.
The array indexed numerically
Numerically indexed array is simply a list of items indicated each by a single numerical index. The first element of the array will be marked with the index 0, the second by the index 1, the third by the index 2 and so on.
To access an element of the array, just refer to it like this: $array[0], $array [1], $array [2] … back to our previous example:
Reading a value in a array to digital keys
<?php // Declare an array indexed numerically $vegetables = array ('carrot', 'pepper', 'Onion', 'cabbage'); // Add a vegetable in spreadsheet $vegetables [] = 'salad'; // Display Onion echo $vegetables [2];
?>
The associative array
It appeared to address the weaknesses of the array with numerical index. Indeed for the latter, it is essential to know its location to reach the value and for a programmer is not always the case. Further, a value indicated by an index less sense than that value indicated by a chained key.
An associative array is an array composed of key pairs chained / value. Each key is a referenced value. We saw earlier how to declare an associative array and associate referenced by key values.
To access one of the values in the array, just refer to it as follows: $array [‘key’]. In our previous example, we could display the identity of the person in this way:
Reading values in an associative array
<?php // Display the values of the associative array echo 'First Name : ', $identity ['firstname'], '<br/>'; echo 'Last Name :', $identity ['lastname'], '<br/>'; echo 'Age :', $identity ['age'], '<br/> years'; echo 'Size :', $identity ['size'], 'cm'; ?>
This will effectively displayed on the screen:
Result of the script
First Name: Karan
Last Name: Johar
Age: 19 years
Size: 180 cm
Note: it is possible to mix and associative arrays numerically indexed arrays.
Multidimensional Arrays
We have just seen how to create simple array to one dimension. They are also called “vectors”. But it is also possible to create multidimensional arrays. They are arrays of arrays. Consider a simple example. We will design a “matrix” (2D array) representing a part of a winning game of noughts and crosses. A tic tac toe game is visually represented by a array of 3 rows of 3 columns. Our matrix will have its characteristics.
Example of creating a matrix (2D array)
<?php // Declare the array $array = array (); $array [0] = array ('X', 'Y', 'X'); $array [1] = array ('X', 'X', 'Y'); $array [2] = array ('X', 'Y', 'O'); ?>
Explanations:
To create a matrix, we need to put in place an array of arrays. Each numerical index (array row), we associate a new array of 3 squares (representing the 3 columns of the line). If we want to reach the middle of the box of Tic Tac Toe game we have to get to the line 2 (index 1) and column 2 (index 1). Which give :
Access to the coordinate value (1,1) <?php // Return X echo $array [1] [1]; ?>
Particular array: string
When one declares a variable that stores a string, we naturally this:
//Declaring a string <?php $string = 'Hello World'; ?>
For this syntax, PHP will actually declare a numerically indexed array that contains N 1 character boxes. So we can go directly to a letter of the string this way:
Playing a character in the character string array
<?php $string = 'Hello World';
echo $string [3]; // Display the letter ‘l’
?>
By retaining this clever concept, we will subsequently treat strings more easily.
Navigating a array
As in any other programming language, the route array is done using loops. PHP has its own control structure to browse the contents of a array. This is the foreach (). It is a special loop which advances pointer array each iteration. It has been integrated since version 4 of PHP and comes in two syntaxes;
array with foreach ()
<? Php
// Display the values of an array
foreach ($MyArray as $value)
{
echo $value, ‘<br/>’;
}
// Display the key / value pairs
foreach ($MyArray as $key => $value)
{
echo $key, ‘:’, $value, ‘<br/>’;
}
?>
This structure takes in parameter the name of the array to go and retrieve the data you need (or only key values and values). In the first syntax, the value of the current element of the array is directly assigned to the variable $ value. In the second, the current key of the array element is assigned to the variable $ key and value stored in the variable $ value.
Note: foreach () works on a copy of the original array.
We could browse our two example arrays ($ vegetables and $ identity) using foreach (). Thus, we get the following code:
Browse the arrays $ vegetables and $ identity
<?php // Display vegetables foreach ($vegetables as $value) {
echo $value, ‘<br/>’;
}
// Display the identity of the person
foreach ($identity as $key => $value) {
echo $key, ‘:’, $value, ‘<br/>’;
}
?>
Note also that it is quite possible to browse a array through another loop. Take the example of the for loop () to illustrate this.
Navigating a array with indexes contiguous digital loop ()
<?php
// Calculate the size of the array $ vegetables
$ArraySize = sizeof ($vegetables);
// Browse the array
for ($ i = 0; $ i <$ArraySize; $ i ++)
{
echo $vegetables [$i] ‘<br/>’;
}
?>
This method has a drawback. For associative arrays or digital arrays noncontiguous indexes, it is difficult to get the key of the current element traversed. The solution is to use specific functions of array manipulation to get the keys.
View the content of a array
When one develops, it often happens that we want to display the contents of a array in order to debug a program. For this, PHP introduces the print_r () function that provides this function. To comply with the indentation on the display, we prefixes the result of this function with the <pre> and </ pre>. The following code shows the contents of our associative array $ identity.
Viewing the contents of an array <?php echo '<pre>'; print_r ($identity); echo '</ pre>'; ?>
The product result will be:
Result of the script
Array
(
[Name] => Karan
[Firstname] => Johar
[Age] => 19
[Student] => 1
[Size] => 180
)
Brackets are the keys and to the right of the arrows associated values.
Array Operations
The advantage of using arrays to organize its applications, is that it then allows to operate on them. Indeed, PHP offers a series of native functions able to manipulate these structures. Here are some frequently used and one particularly useful:
• count () and sizeof () both return the size of the array passed as parameter.
• sort () sorts the array elements from smallest to largest.
• rsort () sorts the array elements from largest to smallest.
• in_array () to check that a value is present in a array.
• array_rand () extracts one or more values in the array at random.
• current () returns the value of the current element of the array (where the cursor is located)