Matrices in PHP
A matrix is a place where we store data, in the same way as in the variables, but with the possibility of storing several data (values) arranged in different compartments, instead of a single data, as in the case of a variable.
The matrices: Many provisional data
A package of variables
A matrix is a place where we store data, in the same way as in the variables, but with the possibility of storing several data (values) arranged in different compartments, instead of a single data, as in the case of a variable.
We could say that, if a variable was a bicycle that carried a single small box with its load, the matrices would be equivalent to a truck loaded with tens, hundreds or thousands of boxes, each one keeping a different data, but all within the same container (the truck).
Another comparison: if a variable was a single shelf (and very small) in which we could only save a single book, comparatively, a matrix would be equivalent to a large shelf in which dozens of books enter or, even, a complete library, with Dozens of shelves at once.
Many books, many shelves, but all within the same library, of the same container element.
Let's see a couple of examples that will clarify a little more the difference between a variable and a matrix.
This code declares and awards value to a variable:
<?php
$number=514;
print($number);
//write 514
?>
El nombre de la variable es $numero, y el valor almacenado en este momento es el número 514.
Ahora veamos la diferencia en el caso de definir una matriz:
En el siguiente código, declararemos una matriz de tres elementos o celdas, a la que denominaremos $numeros.
<?php
$numbers[0]=75;
$numbers[1]=90;
$numbers[2]=45;
print ($numbers[0]."<br />".$numbers[1]."<br />".$numbers[2]);
//writeá: 75<br />90<br />45
?>
In this case, the name of the matrix is $ numbers, and it has three internal subdivisions which we will call "elements" or "cells" (each element of the matrix is one of the three "boxes" that we see in the previous image) .
Note that each element (or cell) is a pair that consists of an index (identifier) and a value.
The first element of this matrix has as index the number 0 and as a value a 75.
The second element, with index 1, stores a 90 and, the third index element 2, stores a number 45 inside it.
That is, unlike a variable, a matrix stores several data, each with the same matrix name ($ numbers, in this case), but with an always different, unique index name.
It would be similar to a shelf in a library, which we call "English books." If I want the first of the books on that shelf, I would ask it by saying "the first book of the English shelf"; if I wanted the second, I would say "the second book of the English shelf"; in programming in PHP, we could refer to that situation with this notation $english_books [1] and, if I wanted to reach the second book, I would refer to it as $english_books [2], and so on.
The only point that conflicts with real life is that the indexes that identify each cell of a matrix, in PHP, are not numbered from 1 onwards, as in real life (we would never ask for "the zero book of the shelf ", we ask the" first ", the" 1 "), but in PHP they are numbered from scratch. The first cell is [0] (reads "subzero"). The second is the "sub 1", the third is the "sub 2", and so on, maintaining that "shift" of a digit".
Let's see a second example of a matrix:
<?php
$countries[0]="Afganistan";
$countries[1]="Albania";
$countries[2]="Alemania";
$countries[3]="Andorra";
$countries[4]="Angola";
print ($countries[0]."<br />".$countries[1]."<br />".$countries[2]."<br />".$countries[3]."<br />".$countries[4]);
//writeá: Afganistan<br />Albania<br />Alemania<br />Andorra<br />Angola
?>
It will be extremely common to use matrices as a temporary store of data from a permanent data warehouse, such as a database or a plain text file.
Different functions of PHP will be responsible for locating data read from a database (such as the list of countries to display them in an HTML selection menu of a form, for example, or the list of the different products of a site). of electronic commerce, including its name, description, price, image, etc.), and it will be very easy to work with that matrix as a temporary repository of data, typically using a loop to traverse it.
Numerical indexes
Matrices can use two types of indexes: numerical (those we have seen so far) and alphanumeric ones.
We will begin to see how data is loaded into arrays of numerical indexes.
There are different ways to "initialize" a matrix of numerical indexes (that is, to give an index and a value to each of its cells, that is, to place data inside it). We can perform this task explicitly, implicitly, by mixing both forms, or using the array constructor. Let's see, below, each of these possibilities.
Explicit statement:
Each index of the matrix is explicitly declared, placing in square brackets the desired number of indexes for the value that we immediately assign to it:
$countries[0]=”afganistan”;
$countries[1]=”Albania”; //etc.
If then we need to access a stored data, we did it by specifying its index, in this way.
Si luego precisamos acceder a un dato almacenado, lo hacíamos especificando su índice, de esta manera:
print($countries[0]);
print($countries[1]); //etc.
And so on, specifying the number of indexes that will identify each data.
Implicit statement:
But we could also have done the same example with an implicit declaration of indices, in the following way (note the empty square brackets in the first line):
<?php
$countries[]="Afganistan"; //this is an implicit statement, leaving empty.
$countries[1]="Albania";
$countries[2]="Alemania";
$countries[3]="Andorra";
$countries[4]="Angola";
print($countries[0]."<br />".$countries[1]."<br />".$countries[2]."<br />".$countries[3]."<br />".$countries[4]);
//writeá: Afganistan<br />Albania<br />Alemania<br />Andorra<br />Angola
?>
If we omit the index numbers when placing values within the cells of the matrix, the PHP interpreter will automatically assign one to it, and place correlative numbers, starting with the smallest possible number (a zero, unless we specify something else) for the first cell of the matrix.
Note that, by leaving empty the square brackets, you simply omit one step, which is to assign a specific number to the index, but, anyway, the PHP interpreter completes it automatically.
Therefore, at the time you want to read that data, it is still essential to specify which cell of the matrix we want to read.
It would not work if we do this:
print $countries[]; //it would be necessary to indicate which cell to show
Since we are saying which of the cells of the matrix we want to show. Always within the echo or print we must explicitly specify the index to which we want to access.
Mixed explicit and implicit statement:
It could also happen that we would like to specify a particular index for the first cell of the matrix, and then let the interpreter continue to place the indexes automatically, but from that initial value that we specify:
<?php
$day[1]="Monday"; //we specify an initial index (the "1" in this case), and then we let PHP place the others automatically
$day[]="Tuesday";
$day[]="Wednesday";
$day[]="Thursday";
$day[]="Friday";
print ($day[1]."<br />".$day[2]."<br />".$day[3]."<br />".$day[4]."<br />".$day[5]);
//print Monday<br />Tuesday<br />Wednesday<br />Thursday<br />Friday
?>
Having specified one of the indexes, but not the following ones, PHP continues the numbering from the value following the last specified index.
The array functions
This implicit declaration of numerical indexes is the same as PHP uses when we use a much simpler and shorter way of declaring matrices, by using the function called array, whose syntax we will see below:
<?php
$countries=array("Argentina", "Uruguay", "Chile", "Perú");
//create a matrix called $ countries of four elements with indexes numbered from zero
$lottery=array(23,8,36,12,99);
//create an array of five elements with indexes numbered from zero
$user=array("John Pérez", 24, "casado", 800);
//create an array of four elements with indexes numbered from zero
?>
As we see in the last case, a single matrix can store data of different types (characters, integers, decimals, etc.) and, therefore, it is necessary to put the texts in quotes so that PHP knows what they are, texts, and no numbers.
Also note that just one comma separates one data from the other.
As in the mixture of explicit and implicit allocation of indexes previously seen, when we use the array function we can also force the index of one of the elements of the matrix (it does not necessarily have to be the first of them), and that is done with the operator => as follows:
<?php
$countries=array("Argentina", 10 => "Uruguay", "Chile", "Perú");
//be a matrix called $ countries of four elements, whose first element has a "0" as index, the second a "10" and then the rest continues with "11" and "12"
?>
Non-consecutive numerical indexes
It is quite common for the indexes assigned to an array to be skipped, non-consecutive numbers, such as item codes. In that case, as we add data to the vector, it may happen that the indexes are not consecutive and are disordered.
For example:
<?php
$products[1234]="42 inch LG TV";
$products[145]="Sony 29-inch TV";
$products[899]="12 volt portable TV";
?>
This would be a matrix of numerical indexes, not consecutive ones.
In this example, the first index e 1234 and the one following it is not 1235, as would be expected if it were consecutive. It is 145 and, then it does not follow 146 either, but another number anyone.
We will see how to interact with matrices that have this type of numerical indexes disordered or non-consecutive, when we learn to traverse the matrices by means of loops.
Alphanumeric indexes
In many cases, especially when working with databases, defining the indexes of the matrix with text strings (alphanumeric) instead of using numbers will be very useful to facilitate the reading of the code.
In PHP it can be done as follows:
<?php
$data["name"]="John Pérez";
$data["age"]=24;
$data["state"]="married";
$data["salary"]=800;
print ($data["name"]); //write: Juan Pérez
?>
This reads "sub name data", "sub age data", etc.
Note that inside the brackets, instead of numbers, we have placed descriptive words of what that cell contains. Those are the alphanumeric indexes or identifiers. Like all PHP text, it must be enclosed in quotes. They are highly recommended to facilitate reading, to realize what each cell of a matrix contains.
Matrix automatically defined by the PHP interpreter
A special case within the matrices of alphanumeric indexes, are those matrices that the PHP interpreter declares and completes with data automatically, without us having to do anything, just read them and use the information they provide us.
Since the list of possible values of alphanumeric indexes of these matrices is very extensive (sometimes, dozens of possible values in each matrix), it is recommended to consult the official PHP reference manual online, at http://www.php.net/ adding the name of the matrix that we want to know at the end of the URl, for example:
http://www.php.net/_server
Next, we will see a table with the names of these matrices defined by the PHP interpreter:
MATRIZ | CONTENT | USE EXAMPLES |
---|---|---|
$_SERVER |
It contains information available on the Web server: routes, HTTP headers sent by the user's browser such as the browser used, the user's IP address, etc. |
echo $_SERVER [‘HTTP_USER_AGENT’]; |
$_ENV |
It contains information about the environment in which the PHP interpreter is being used (name of the computer, server, etc). |
echo $_ENV [‘HOSTNAME’]; |
$_SESSION |
It contains the session variables that we have declared. The index is the name of the variable. |
echo $_SESSION [‘mi_variable’]; |
$_GET |
It contains the variables sent to the server through links (attached to an HTTP request). The index is the name of the variable. |
echo $_GET [‘mi_variable’]; |
$_POST |
It contains the variables sent using forms that declare the "post" method. The index is the name of the variable. |
echo $_POST [‘mi_variable’]; |
$_COOKIE |
It contains the variables stored by the cookie user's browser. The index is the name of the variable. |
echo $_COOKIE [‘mi_variable’]; |
$_REQUEST |
It contains the variables stored in the three previous matrices: $ _GET, $ _POST and $ _COOKIE. That is, all the variables that were sent by the user's browser to the server. |
echo $_REQUEST [‘mi_variable’]; |
$_FILES |
Contains information about files that have been sent using a form that has a file type input control. |
echo $_FILES [‘el_archivo’][name]; |
$GLOBALS |
It contains information about all the variables defined, either automatically by the server, as defined by ourselves. Note that it is the only automatically defined matrix that does not have a hyphen in front of its name. |
Echo $GLOBALS [‘mi_variable’]; |
Many of the values of these matrices are not available in all servers, since they depend on the server administrator having enabled their use, so it is not possible to make a complete list that is available under all circumstances. It will have to be tested on each server before using data from these matrices.
Note that all the names of these matrices-except one-start with a hyphen, and that all these matrices defined by the PHP interpreter have their names written in all capital letters, as if they were a constant; that allows us to easily differentiate them within our code from the other matrices that we have declared ourselves.
It will be very common now that we use in our codes data obtained from these matrices defined automatically by the PHP interpreter.
ChatGPT Free
Ask questions on any topic
CITE ARTICLE
For homework, research, thesis, books, magazines, blogs or academic articles
APA Format Reference:
Delgado, Hugo. (2019).
Matrices in PHP.
Retrieved Oct 06, 2024, from
https://disenowebakus.net/en/php-matrix