3. The Basics of PHP
3.1. The script directory structure

3.2. PHP Configuration
PHP comes preconfigured via a text file [php.ini]. All of these settings can be changed programmatically. PHP configuration greatly influences script execution. It is therefore important to understand it. The following script [phpinfo.php] allows you to do so:
Comments
- line 3: the [phpinfo] function displays the PHP configuration;
Execution results
The [phpinfo] function displays over 800 configuration lines here. We won’t comment on them because most pertain to advanced PHP usage. An important line is line 13 above: it indicates which [php.ini] file was used to configure the PHP you’ll use to run your scripts. If you want to change the PHP runtime configuration, this is the file you need to edit. There are many comments in this file explaining the role of the various settings.
3.3. A first example
3.3.1. The code
Below is a program [bases-01.php] that demonstrates the basic features of PHP.
<?php
// this is a comment
// variable used without being declared
$nom = "dupont";
// a screen display
print "nom=$nom\n";
// an array with elements of different types
$tableau = array("un", "deux", 3, 4);
// its number of elements
$n = count($tableau);
// a loop
for ($i = 0; $i < $n; $i++) {
print "tableau[$i]=$tableau[$i]\n";
}
// initialize 2 variables with the contents of an array
list($chaine1, $chaine2) = array("chaine1", "chaine2");
// concatenation of the 2 strings
$chaine3 = $chaine1 . $chaine2;
// result display
print "[$chaine1,$chaine2,$chaine3]\n";
// use function
affiche($chaine1);
// the type of a variable can be known
afficheType("n", $n);
afficheType("chaine1", $chaine1);
afficheType("tableau", $tableau);
// the type of a variable can change at runtime
$n = "a changé";
afficheType("n", $n);
// a function can return a result
$res1 = f1(4);
print "res1=$res1\n";
// a function can render a table of values
list($res1, $res2, $res3) = f2();
print "(res1,res2,res3)=[$res1,$res2,$res3]\n";
// we could have retrieved these values in a table
$t = f2();
for ($i = 0; $i < count($t); $i++) {
print "t[$i]=$t[$i]\n";
}
// testing
for ($i = 0; $i < count($t); $i++) {
// displays only channels
if (getType($t[$i]) === "string") {
print "t[$i]=$t[$i]\n";
}
}
// == and === comparison operators
if("2"==2){
print "avec l'opérateur ==, la chaîne 2 est égale à l'entier 2\n";
}else{
print "avec l'opérateur ==, la chaîne 2 n'est pas égale à l'entier 2\n";
}
if("2"===2){
print "avec l'opérateur ===, la chaîne 2 est égale à l'entier 2\n";
}
else{
print "avec l'opérateur ===, la chaîne 2 n'est pas égale à l'entier 2\n";
}
// other tests
for ($i = 0; $i < count($t); $i++) {
// displays only integers >10
if (getType($t[$i]) === "integer" and $t[$i] > 10) {
print "t[$i]=$t[$i]\n";
}
}
// a while loop
$t = [8, 5, 0, -2, 3, 4];
$i = 0;
$somme = 0;
while ($i < count($t) and $t[$i] > 0) {
print "t[$i]=$t[$i]\n";
$somme += $t[$i]; //$somme=$somme+$t[$i]
$i++; //$i=$i+1
}//while
print "somme=$somme\n";
// end of program
exit;
//----------------------------------
function affiche($chaine) {
// displays $chaine
print "chaine=$chaine\n";
}
//poster
//----------------------------------
function afficheType($name, $variable) {
// displays the type of $variable
print "type[variable $" . $name . "]=" . getType($variable) . "\n";
}
//afficheType
//----------------------------------
function f1($param) {
// adds 10 to $param
return $param + 10;
}
//----------------------------------
function f2() {
// returns 3 values
return array("un", 0, 100);
}
?>
The results:
nom=dupont
tableau[0]=un
tableau[1]=deux
tableau[2]=3
tableau[3]=4
[chaine1,chaine2,chaine1chaine2]
chaine=chaine1
type[variable $n]=integer
type[variable $chaine1]=string
type[variable $tableau]=array
type[variable $n]=string
res1=14
(res1,res2,res3)=[un,0,100]
t[0]=un
t[1]=0
t[2]=100
t[0]=un
avec l'opérateur ==, la chaîne 2 est égale à l'entier 2
avec l'opérateur ===, la chaîne 2 n'est pas égale à l'entier 2
t[2]=100
t[0]=8
t[1]=5
somme=13
Comments
- line 5: In PHP, you don’t declare variable types. Variables have a dynamic type that can change over time. $name represents the variable with the identifier name;
- line 7: to display output on the screen, you can use the print statement or the echo statement;
- line 9: the keyword array is used to define an array. The variable $name[$i] represents the $i-th element of the $array array;
- line 11: the function count($tableau) returns the number of elements in the $tableau array;
- lines 13–15: a loop. Since this loop contains only one statement, curly braces are optional. In the rest of this document, we will always use curly braces regardless of the number of statements;
- line 14: strings are enclosed in double quotes " or single quotes '. Inside double quotes, the variables $variable are evaluated, but not inside single quotes;
- line 17: the list function allows you to group variables into a list and assign a value to them with a single assignment operation. Here, $chaine1="chaine1" and $chaine2="chaine2";
- line 19: the . operator is the string concatenation operator;
- lines 83–86: the keyword `function` defines a function. A function may or may not return values using the `return` statement. The calling code can ignore or retrieve the results of a function. A function can be defined anywhere in the code.
- line 92: the predefined function getType($variable) returns a string representing the type of $variable. This type may change over time;
- Line 45: The === operator performs a strict comparison of two elements: they must be of the same type to be compared. The == operator is less strict: two elements can be equal without being of the same type. This is demonstrated by the statements on lines 50–60. In the case of the == operator, the comparison is performed after casting both elements being compared to the same type. Implicit conversions then take place. It is quite easy to “forget” about these implicit conversions and thus end up with unexpected results, such as discovering that a condition is true when you expected it to be false. To avoid this pitfall, we will systematically use the === comparison operator;
- line 64: you can also use the Boolean operators or and !;
- line 69: instead of the array() notation, you can use the [] notation to initialize an array in PHP 7;
- line 80: the predefined exit function stops the script from running;
- line 107: the ?> tag marks the end of the PHP script. It is not essential. Furthermore, in a web context, it can cause problems if followed by spaces or line breaks, which are difficult to detect because they are not visible in a text editor. Therefore, in the rest of this document, we will consistently omit this tag;
Note: In this document, we will use the keyword [print] to display text on the console. Another way to do the same thing is to use the keyword [echo]. There are subtle differences between these two keywords, but in the context of this document, there will be none. So if you prefer to use [echo], then do so.
3.3.2. Using NetBeans
NetBeans issues various warnings that are worth checking. Let’s take the example of the [bases-01.php] script:

On line 5, NetBeans issues a warning that the file does not comply with the PSR-1 recommendation (PHP Standard Recommendations No. 1). PSRs are recommendations for producing standard code to facilitate interoperability and maintenance of code written by different people. It can be annoying to get warnings if you want to deliberately break the standards, for example because the project team has different ones. What you want to check or not with NetBeans is configurable:

- in [5], you’ll find the elements you want to check with NetBeans;
- in [6], the severity level assigned to the error reported by NetBeans;

In [7], you can see that we’ve requested to check that the code follows the PSR-0 and PSR-1 recommendations. Nothing is mandatory. When learning the language, it’s advisable to check as many of the options offered by NetBeans as possible. You’ll learn a lot that way. You can then adapt these NetBeans checks to your project team’s coding standards.
Let’s look at the PSR-1 coding standards [8, 9]:
Option | Check |
| Class constants MUST be declared in all uppercase with underscore separators. Ex: const TAUX_TVA |
| Method names MUST be declared in camelCase(). Ex: public function executeBatchTaxes{} |
| Property names SHOULD be declared in $StudlyCaps, $camelCase, or $under_score format (consistently within a scope) Ex: public AnnualSalary (StudlyCaps), public annualSalary (camelCase), public annual_salary (underscore) |
| A file SHOULD declare new symbols and cause no other side effects, or it SHOULD execute logic with side effects, but SHOULD NOT do both. |
| Type names MUST be declared in StudlyCaps (Code written for 5.2.x and earlier SHOULD use the pseudonamespacing convention of Vendor_ prefixes on type names). Each type is in its own file and is in a namespace of at least one level: a top-level vendor name. Ex: class ScholarshipStudent {} |
The PSR-1/4 recommendation states that a PHP file must contain:
- either a type declaration (classes, interfaces);
- or executable code without declarations of new types;
There are other PHP recommendations not enforced by NetBeans: PSR-3, PSR-4, PSR-6, PSR-7, and PSR-13.
For simplicity, not all examples in this document adhere to the PSR-1 recommendation, as this would require splitting class and interface code into separate files, which is too cumbersome for basic examples. It is therefore easier to put everything in a single file. For the example application presented as the central theme of this document, we have endeavored to follow the PSR-1 recommendation as closely as possible.
Some NetBeans warnings indicate a potential error:

The [Uninitialized Variables] warning indicates a probable error, often a typo in a variable name. The same applies to the [Unused Variables] warning.
Finally, it is recommended that you check all NetBeans warnings, which are indicated by a banner in the left margin of the code and a yellow dash in the right margin:


3.4. Variable scope
3.4.1. Example 1
The [bases-02.php] script is as follows:
<?php
// variable scope
function f1() {
// we use the global variable $i
global $i;
$i++;
$j = 10;
print "f1[i,j]=[$i,$j]\n";
}
function f2() {
// we use the global variable $i
global $i;
$i++;
$j = 20;
print "f2[i,j]=[$i,$j]\n";
}
function f3() {
// we use a local variable $i
$i = 4;
$j = 30;
print "f3[i,j]=[$i,$j]\n";
}
// tests
$i = 0;
$j = 0; // these two variables are known only to a function f
// only if it explicitly declares with the global instruction
// she wants to use them
f1();
f2();
f3();
print "test[i,j]=[$i,$j]\n";
The results:
Comments
- Lines 29–30: define two variables, $i and $j, in the main program. These variables are not known within the functions. Thus, in line 9, the variable $j in function f1 is a local variable of function f1 and is different from the variable $j in the main program. A function can access a variable $variable in the main program using the keyword global;
- line 7, the statement refers to the global variable $i of the main program;
3.4.2. Example 3
The script [bases-03.php] is as follows:
<?php
// the scope of a variable is global to code blocks
$i = 0; {
$i = 4;
$i++;
}
print "i=$i\n";
The results:
Comments
In some languages, a variable defined inside curly braces has the scope of those braces: it is not known outside of them. The results above show that this is not the case in PHP. The variable $i defined on line 5 inside the curly braces is the same as the one used on lines 4 and 8 outside of them.
3.5. Type Changes
Variables in PHP do not have a fixed type. Their type can change during execution depending on the value assigned to the variable. In operations involving data of various types, the PHP interpreter performs implicit conversions to bring the operands into a common type. These implicit conversions, if unknown to the developer, can be a source of errors that are difficult to detect. Below is a script [bases-04.php] demonstrating implicit and explicit conversions:
<?php
// strict types for passing parameters
declare(strict_types=1);
// implicit type changes
// type -->bool
print "Conversion vers un booléen------------------------------\n";
showBool("abcd", "abcd");
showBool("", "");
showBool("[1, 2, 3]", [1, 2, 3]);
showBool("[]", []);
showBool("NULL", NULL);
showBool("0.0", 0.0);
showBool("0", 0);
showBool("4.6", 4.6);
function showBool(string $prefixe, $var) : void {
print "(bool) $prefixe : ";
// conversion of $var to Boolean is automatic in the following test
if ($var) {
print "true";
} else {
print "false";
}
print "\n";
}
Comments
- line 4: requires strict type checking of a function’s parameters when specified;
- line 18: the [showBool] function is intended to demonstrate the implicit (automatic) conversion performed by the PHP interpreter when a value of any type must be converted to a boolean (line 21);
- line 18: the $var parameter has no assigned type. The actual parameter can therefore be of any type. The $prefix parameter, on the other hand, must be of type string. The showBool function returns no value (void);
- line 21: in the if($var) statement, the value of $var must be converted to a boolean for the if to be evaluated. Surprisingly, the PHP interpreter has a solution for any type of value given to it;
- lines 9–16: the value of the [showBool] function’s parameter will be, in turn:
- line 9: a non-empty string: result TRUE (case is not important, TRUE=true);
- line 10: an empty string: result FALSE;
- line 11: a non-empty array: result TRUE;
- line 12: an empty array: result FALSE;
- line 14: the real number 0: result FALSE;
- line 15: the integer 0: result FALSE;
- line 16: a real number (or integer) other than 0: result TRUE;
This is what the screen displays show:
Conversion vers un booléen------------------------------
(bool) abcd : true
(bool) : false
(bool) [1, 2, 3] : true
(bool) [] : false
(bool) NULL : false
(bool) 0.0 : false
(bool) 0 : false
(bool) 4.6 : true
Let's continue with the script code:
//
// implicit changes from string type to numeric type
// string --> number
print "Conversion chaîne vers nombre------------------------------\n";
showNumber("12");
showNumber("45.67");
showNumber("abcd");
function showNumber(string $var) : void {
$nombre = $var + 1;
var_dump($nombre);
print "($var): $nombre\n";
}
Comments
- line 9: the [showNumber] function takes a string parameter and returns no result (void);
- line 10: this parameter is used in an arithmetic operation, which will force the PHP interpreter to attempt to convert $var into a number;
- line 5: will convert the string “12” into the integer 12;
- line 6: will convert the string “45.67” into the floating-point number 45.67;
- line 7: will issue a warning but will still convert the string “abcd” into the number 0;
Here are the results of the execution:
Let's continue with the script code:
// changements explicites de type
// vers int
showInt("12.45");
showInt(67.8);
showInt(TRUE);
showInt(NULL);
function showInt($var) : void {
print "paramètre : ";
var_dump($var);
print "\n";
print "résultat de la conversion : ";
var_dump((int) $var);
print "\n";
}
Comments
- Line 21: The [showInt] function takes a parameter of any type and does not return a result. It attempts to convert the parameter $var to an integer on line 26. Generally, to cast a variable $var to type T, we write (T) $var, where T can be: int, integer, bool, boolean, float, double, real, string, array, object, unset;
- line 16: converts the string “12.45” to the integer 12;
- line 17: converts the real number 67.8 to the integer 67;
- line 18: converts the boolean TRUE to the integer 1 (the boolean FALSE to the integer 0);
- line 19: converts the NULL pointer to the integer 0;
This is what the screen displays:
We continue our study of the script with the explicit conversion of values to the float type:
// to float
showFloat("12.45");
showFloat(67);
showFloat(TRUE);
showFloat(NULL);
function showFloat($var) : void {
print "paramètre : ";
var_dump($var);
print "\n";
print "résultat de la conversion : ";
var_dump((float) $var);
print "\n";
}
Comments
- line 35: the [showFloat] function takes a parameter of any type and does not return a result;
- line 40: the value of this parameter is explicitly converted to a float;
- line 30: the string “12.45” is converted to the floating-point number 12.45;
- line 31: the integer 67 is converted to the real number 67;
- line 32: the boolean TRUE is converted to the real number 1 (the value FALSE to the number 0);
- line 33: the NULL pointer is converted to the real number 0;
This is shown by the screen output:
We continue the script overview by examining conversions to the string type:
// to string
showstring(5);
showString(6.7);
showString(FALSE);
showString(NULL);
function showString($var) : void {
print "paramètre : ";
var_dump($var);
print "\n";
print "résultat de la conversion : ";
var_dump((string) $var);
print "\n";
}
- line 49: the [showString] function takes a parameter of any type and does not return a result;
- line 54: the parameter value is converted to a string;
- line 44: the integer 5 will be converted to the string "5";
- line 45: the floating-point number 6.7 will be converted to the string "6.7";
- line 46: the boolean FALSE will be converted to an empty string;
- line 47: the NULL pointer is converted to an empty string;
Here are the screen results:
3.6. Arrays
3.6.1. Classic one-dimensional arrays
The script [bases-05.php] is as follows:
<?php
// classic paintings
// initialization
$tab1 = array(0, 1, 2, 3, 4, 5);
// routes - 1
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++) {
print "tab1[$i]=$tab1[$i]\n";
}
// routes - 2
print "tab1 a " . count($tab1) . " éléments\n";
reset($tab1);
while (list($clé, $valeur) = each($tab1)) {
print "tab1[$clé]=$valeur\n";
}
// add elements
$tab1[] = $i++;
$tab1[] = $i++;
// routes - 3
print "tab1 a " . count($tab1) . " éléments\n";
$i = 0;
foreach ($tab1 as $élément) {
print "tab1[$i]=$élément\n";
$i++;
}
// delete last item
array_pop($tab1);
// routes - 4
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++) {
print "tab1[$i]=$tab1[$i]\n";
}
// delete first element
array_shift($tab1);
// routes - 5
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++) {
print "tab1[$i]=$tab1[$i]\n";
}
// addition at end of table
array_push($tab1, -2);
// routes - 6
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++) {
print "tab1[$i]=$tab1[$i]\n";
}
// addition at the beginning of the table
array_unshift($tab1, -1);
// routes - 7
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++) {
print "tab1[$i]=$tab1[$i]\n";
}
The results:
tab1 a 6 éléments
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1 a 6 éléments
Deprecated: The each() function is deprecated. This message will be suppressed on further calls in C:\Data\st-2019\dev\php7\php5-exemples\exemples\exemple_04.php on line 14
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1 a 8 éléments
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1[6]=6
tab1[7]=7
tab1 a 7 éléments
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1[6]=6
tab1 a 6 éléments
tab1[0]=1
tab1[1]=2
tab1[2]=3
tab1[3]=4
tab1[4]=5
tab1[5]=6
tab1 a 7 éléments
tab1[0]=1
tab1[1]=2
tab1[2]=3
tab1[3]=4
tab1[4]=5
tab1[5]=6
tab1[6]=-2
tab1 a 8 éléments
tab1[0]=-1
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1[6]=6
tab1[7]=-2
Comments
The program above demonstrates operations for manipulating an array of values. There are two notations for arrays in PHP:
Array 1 is called an array, and array 2 is called a dictionary or associative array, where elements are denoted as key => value. The notation $opposites["beautiful"] refers to the value associated with the key "beautiful." Here, that value is the string "ugly." Array 1 is simply a variant of the dictionary and could be written as:
This gives us $array[2] = "three". Ultimately, these are all dictionaries. In the case of a standard array of n elements, the keys are the integers in the range [0, n-1].
- line 14: the each($array) function allows you to iterate over a dictionary. On each call, it returns a (key, value) pair from it. As shown in line 10 of the results, the each function is now deprecated in PHP 7;
- line 13: the reset($dictionary) function sets the each function to the first (key, value) pair in the dictionary.
- line 14: the while loop stops when the each function returns an empty pair at the end of the dictionary. An implicit conversion is at work here: the empty pair is converted to the boolean FALSE;
- line 18: the notation $array[]=value adds the element value as the last element of $array;
- line 23: the array is iterated over using a foreach loop. This syntax allows you to iterate over a dictionary—and thus an array—using two different syntaxes:
The first syntax returns a (key,value) pair on each iteration, while the second syntax returns only the value element of the dictionary.
- line 28: the array_pop($array) function removes the last element from $array;
- line 35: the array_shift($array) function removes the first element from $array;
- line 42: the array_push($array,value) function adds value as the last element of $array;
- line 49: the array_unshift($array,value) function adds value as the first element of $array;
3.6.2. The dictionary or associative array
The script [bases-06.php] is as follows:
<?php
// dictionaries
$conjoints = ["Pierre" => "Gisèle", "Paul" => "Virginie", "Jacques" => "Lucette", "Jean" => ""];
// routes - 1
print "Nombre d'éléments du dictionnaire : " . count($conjoints) . "\n";
reset($conjoints);
while (list($clé, $valeur) = each($conjoints)) {
print "conjoints[$clé]=$valeur\n";
}
// dictionary sorting on key
ksort($conjoints);
// routes - 2
reset($conjoints);
while (list($clé, $valeur) = each($conjoints)) {
print "conjoints[$clé]=$valeur\n";
}
// list of dictionary keys
$clés = array_keys($conjoints);
for ($i = 0; $i < count($clés); $i++) {
print "clés[$i]=$clés[$i]\n";
}
// list of dictionary values
$valeurs = array_values($conjoints);
for ($i = 0; $i < count($valeurs); $i++) {
print "valeurs[$i]=$valeurs[$i]\n";
}
// key search
existe($conjoints, "Jacques");
existe($conjoints, "Lucette");
existe($conjoints, "Jean");
// deleting a key-value
unset($conjoints["Jean"]);
print "Nombre d'éléments du dictionnaire : " . count($conjoints) . "\n";
foreach ($conjoints as $clé => $valeur) {
print "conjoints[$clé]=$valeur\n";
}
// end
exit;
function existe($conjoints, $mari) {
// checks whether the key $mari exists in the dictionary $conjoints
if (isset($conjoints[$mari])) {
print "La clé [$mari] existe associée à la valeur [$conjoints[$mari]]\n";
} else {
print "La clé [$mari] n'existe pas\n";
}
}
The results:
Nombre d'éléments du dictionnaire : 4
Deprecated: The each() function is deprecated. This message will be suppressed on further calls in C:\Data\st-2019\dev\php7\php5-exemples\exemples\exemple_05.php on line 8
conjoints[Pierre]=Gisèle
conjoints[Paul]=Virginie
conjoints[Jacques]=Lucette
conjoints[Jean]=
conjoints[Jacques]=Lucette
conjoints[Jean]=
conjoints[Paul]=Virginie
conjoints[Pierre]=Gisèle
clés[0]=Jacques
clés[1]=Jean
clés[2]=Paul
clés[3]=Pierre
valeurs[0]=Lucette
valeurs[1]=
valeurs[2]=Virginie
valeurs[3]=Gisèle
La clé [Jacques] existe associée à la valeur [Lucette]
La clé [Lucette] n'existe pas
La clé [Jean] existe associée à la valeur []
Nombre d'éléments du dictionnaire : 3
conjoints[Jacques]=Lucette
conjoints[Paul]=Virginie
conjoints[Pierre]=Gisèle
Comments
The code above applies to a dictionary what we previously saw for a simple array. We will only comment on the new features:
- line 12: the ksort (key sort) function sorts a dictionary in the natural order of the keys;
- line 19: the array_keys($dictionary) function returns the list of the dictionary’s keys as an array;
- line 24: the array_values($dictionary) function returns the list of the dictionary’s values as an array;
- line 43: the isset($variable) function returns TRUE if the $variable has been defined, FALSE otherwise;
- line 33: the unset($variable) function deletes the $variable.
3.6.3. Multidimensional arrays
The [bases-07.php] script is as follows:
<?php
// classic multidimensional tables
// initialization
$multi = array(array(0, 1, 2), array(10, 11, 12, 13), array(20, 21, 22, 23, 24));
// route
for ($i1 = 0; $i1 < count($multi); $i1++) {
for ($i2 = 0; $i2 < count($multi[$i1]); $i2++) {
print "multi[$i1][$i2]=" . $multi[$i1][$i2] . "\n";
}
}
// multidimensional dictionaries
// initialization
$multi = array("zéro" => array(0, 1, 2), "un" => array(10, 11, 12, 13), "deux" => array(20, 21, 22, 23, 24));
// route
foreach ($multi as $clé => $valeur) {
for ($i2 = 0; $i2 < count($valeur); $i2++) {
print "multi[$clé][$i2]=" . $multi[$clé][$i2] . "\n";
}
}
Results:
multi[0][0]=0
multi[0][1]=1
multi[0][2]=2
multi[1][0]=10
multi[1][1]=11
multi[1][2]=12
multi[1][3]=13
multi[2][0]=20
multi[2][1]=21
multi[2][2]=22
multi[2][3]=23
multi[2][4]=24
multi[zéro][0]=0
multi[zéro][1]=1
multi[zéro][2]=2
multi[un][0]=10
multi[un][1]=11
multi[un][2]=12
multi[un][3]=13
multi[deux][0]=20
multi[deux][1]=21
multi[deux][2]=22
multi[deux][3]=23
multi[deux][4]=24
Comments
- line 5: the elements of the $multi array are themselves arrays;
- line 14: the $multi array becomes a (key, value) dictionary where each value is an array;
3.7. Strings
3.7.1. Notation
The script [bases-08.php] is as follows:
<?php
// string notation
$chaine1 = "un";
$chaine2 = 'un';
print "[$chaine1,$chaine2]\n";
?>
Results:
3.7.2. Comparison
The script [bases-09.php] is as follows:
<?php
// strict adherence to function parameter types
declare(strict_types=1);
// comparison function
function compareModele2Chaine(string $chaine1, string $chaine2): void {
// compare string1 and string2
if ($chaine1 === $chaine2) {
print "[$chaine1] est égal à [$chaine2]\n";
} else {
print "[$chaine1] est différent de [$chaine2]\n";
}
}
// string comparison tests
compareModele2Chaine("abcd", "abcd");
compareModele2Chaine("", "");
compareModele2Chaine("1", "");
exit;
Results:
[abcd] est égal à [abcd]
[] est égal à []
[1] est différent de []
Comments
- Line 9 of the code: we could have used the == operator instead of ===. The latter operator is more restrictive in that it requires both operands to be of the same type. Note that here, it could have been replaced by the == operator since the type of both parameters is set to string in the function signature;
3.7.3. Links between strings and arrays
The [bases-10.php] script is as follows:
<?php
// string to array
$chaine = "1:2:3:4";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++) {
print "tab[$i]=$tab[$i]\n";
}
// table to string
$chaine2 = implode(":", $tab);
print "chaine2=$chaine2\n";
// add an empty field
$chaine .= ":";
print "chaîne=$chaine\n";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++) {
print "tab[$i]=$tab[$i]\n";
} // we now have 5 elements, the last being empty
// let's add another empty field
$chaine .= ":";
print "chaîne=$chaine\n";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++) {
print "tab[$i]=$tab[$i]\n";
} // we now have 6 elements, the last two being empty
Results:
tab a 4 éléments
tab[0]=1
tab[1]=2
tab[2]=3
tab[3]=4
chaine2=1:2:3:4
chaîne=1:2:3:4:
tab a 5 éléments
tab[0]=1
tab[1]=2
tab[2]=3
tab[3]=4
tab[4]=
chaîne=1:2:3:4::
tab a 6 éléments
tab[0]=1
tab[1]=2
tab[2]=3
tab[3]=4
tab[4]=
tab[5]=
Comments
- line 5: the explode($separator,$string) function retrieves the fields of $string separated by $separator. Thus, explode(":",$string) returns the elements of $string separated by the string ":" as an array;
- line 12: the implode($separator,$array) function performs the inverse operation of the explode function. It returns a string consisting of the elements of $array separated by $separator;
3.7.4. Regular Expressions
The [bases-11.php] script is as follows:
<?php
// strict type for function parameters
declare (strict_types=1);
// regular expressions in php
// retrieve the various fields of a string
// the model: a sequence of numbers surrounded by any characters
// you only want to retrieve the sequence of digits
$modèle = "/(\d+)/";
// the chain is compared with the model
compareModele2Chaine($modèle, "xyz1234abcd");
compareModele2Chaine($modèle, "12 34");
compareModele2Chaine($modèle, "abcd");
// the model: a sequence of numbers surrounded by any characters
// we want the sequence of digits and the fields that follow and precede them
$modèle = "/^(.*?)(\d+)(.*?)$/";
// the chain is compared with the model
compareModele2Chaine($modèle, "xyz1234abcd");
compareModele2Chaine($modèle, "12 34");
compareModele2Chaine($modèle, "abcd");
// the template - a date in dd/mm/yy format
$modèle = "/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/";
compareModele2Chaine($modèle, "10/05/97");
compareModele2Chaine($modèle, " 04/04/01 ");
compareModele2Chaine($modèle, "5/1/01");
// the model - a decimal number
$modèle = "/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/";
compareModele2Chaine($modèle, "187.8");
compareModele2Chaine($modèle, "-0.6");
compareModele2Chaine($modèle, "4");
compareModele2Chaine($modèle, ".6");
compareModele2Chaine($modèle, "4.");
compareModele2Chaine($modèle, " + 4");
// end
exit;
// --------------------------------------------------------------------------
function compareModele2Chaine(string $modèle, string $chaîne): void {
// compares the $chaîne string with the $modèle model
// the chain is compared with the
$champs = [];
$correspond = preg_match($modèle, $chaîne, $champs);
// displaying results
print "\nRésultats($modèle,$chaîne)\n";
if ($correspond) {
for ($i = 0; $i < count($champs); $i++) {
print "champs[$i]=$champs[$i]\n";
}
} else {
print "La chaîne [$chaîne] ne correspond pas au modèle [$modèle]\n";
}
}
Results:
Résultats(/(\d+)/,xyz1234abcd)
champs[0]=1234
champs[1]=1234
Résultats(/(\d+)/,12 34)
champs[0]=12
champs[1]=12
Résultats(/(\d+)/,abcd)
La chaîne [abcd] ne correspond pas au modèle [/(\d+)/]
Résultats(/^(.*?)(\d+)(.*?)$/,xyz1234abcd)
champs[0]=xyz1234abcd
champs[1]=xyz
champs[2]=1234
champs[3]=abcd
Résultats(/^(.*?)(\d+)(.*?)$/,12 34)
champs[0]=12 34
champs[1]=
champs[2]=12
champs[3]= 34
Résultats(/^(.*?)(\d+)(.*?)$/,abcd)
La chaîne [abcd] ne correspond pas au modèle [/^(.*?)(\d+)(.*?)$/]
Résultats(/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/,10/05/97)
champs[0]=10/05/97
champs[1]=10
champs[2]=05
champs[3]=97
Résultats(/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/, 04/04/01 )
champs[0]= 04/04/01
champs[1]=04
champs[2]=04
champs[3]=01
Résultats(/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/,5/1/01)
La chaîne [5/1/01] ne correspond pas au modèle [/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/]
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/,187.8)
champs[0]=187.8
champs[1]=
champs[2]=187.8
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/,-0.6)
champs[0]=-0.6
champs[1]=-
champs[2]=0.6
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/,4)
champs[0]=4
champs[1]=
champs[2]=4
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/,.6)
champs[0]=.6
champs[1]=
champs[2]=.6
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/,4.)
champs[0]=4.
champs[1]=
champs[2]=4.
Résultats(/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/, + 4)
champs[0]= + 4
champs[1]=+
champs[2]=4
Comments
- Here we use regular expressions to extract various fields from a string. Regular expressions allow us to overcome the limitations of the implode function. The principle is to compare a string to another string called a pattern using the preg_match function:
$correspond = preg_match($modèle, $chaîne, $champs);
The preg_match function returns a Boolean TRUE if the pattern can be found in the string. If so, $fields[0] represents the substring matching the pattern. Furthermore, if pattern contains subpatterns enclosed in parentheses, $fields[1] is the portion of $string corresponding to the first subpattern, $fields[2] is the portion of $string corresponding to the second subpattern, and so on…
Consider the first example. The pattern is defined on line 10: it denotes a sequence of one or more (+) digits (\d) located anywhere in a string. Furthermore, the pattern defines a subpattern enclosed in parentheses;
- Line 12: The pattern /(\d+)/ (a sequence of one or more digits anywhere in the string) is matched against the string "xyz1234abcd". We see that the substring 1234 matches the pattern. Therefore, $champs[0] will be equal to "1234". Additionally, the pattern has subpatterns enclosed in parentheses. We will have $champs[1]="1234";
- line 13: the pattern /(\d+)/ is compared to the string "12 34". We see that the substrings 12 and 34 match the pattern. The comparison stops at the first substring that matches the pattern. Therefore, $champs[0]=12 and $champs[1]=12;
- line 14: the pattern /(\d+)/ is compared to the string "abcd". No match is found;
Let’s explain the patterns used in the rest of the code:
$modèle = "/^(.*?)(\d+)(.*?)$/";
matches the start of the string (^), followed by zero or more (*) arbitrary characters (.), then one or more (+) digits, followed by zero or more (*) arbitrary characters (.). The pattern (.*) matches zero or more arbitrary characters. Such a pattern will match any string. Thus, the pattern /^(.*)(\d+)(.*)$/ will never be found because the first subpattern (.*) will consume the entire string. The pattern (.*?)(\d+) denotes 0 or more arbitrary characters up to the next subpattern (?), in this case \d+. Therefore, the digits are no longer captured by the pattern (.*). The pattern above thus matches [start of string (^), a sequence of any characters (.*?), a sequence of one or more digits (\d+), a sequence of any characters (.*?), end of string ($)].
$modèle = "/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/";
corresponds to [start of string (^), 2 digits (\d\d), the character / (\/), 2 digits, /, 2 digits, a sequence of 0 or more spaces (\s*), end of string ($)].
$modèle = "/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/";
matches start of string (^), 0 or more spaces (\s*), a + or - sign [+|-] occurring 0 or 1 time (?), a sequence of 0 or more spaces (\s*), 1 or more digits followed by a decimal point followed by zero or more digits (\d+\.\d*) or (|) a decimal point (\.) followed by one or more digits (\d+) or (|) one or more digits (\d+), a sequence of 0 or more spaces (\s*)].
Note: The term [space] in regular expressions refers to a set of characters: whitespace, newline \n, tab \t, carriage return \r, form feed \f…
3.8. Functions
3.8.1. Parameter passing mode
The [base-12.php] script is as follows:
<?php
// function parameter step mode
// strict adherence to parameter type
declare(strict_types=1);
function f(int &$i, int $j): void {
// $i will be obtained by reference
// $j will be obtained by value
$i++;
$j++;
print "f[i,j]=[$i,$j]\n";
}
// tests
$i = 0;
$j = 0;
// $i and $j are passed to function f
f($i, $j);
print "test[i,j]=[$i,$j]\n";
Results:
Comments
The code above demonstrates the two ways of passing parameters to a function. Consider the following example:
- line 1: defines the formal parameters $a and $b of function f. This function manipulates these two formal parameters and returns a result;
- line 7: calls the function f with two actual parameters $i and $j. The relationships between the formal parameters ($a, $b) and the actual parameters ($i, $j) are defined by lines 1 and 7:
- &$a: the & symbol indicates that the formal parameter $a will take on the value of the address of the actual parameter $i. In other words, $a and $i are two references to the same memory location. Manipulating the formal parameter $a is equivalent to manipulating the actual parameter $i. This is demonstrated by the code’s execution. This passing mode is suitable for output parameters and large data sets such as arrays and dictionaries. This passing mode is called pass-by-reference.
- $b: The formal parameter $b will take on the value of the actual parameter $j. This is passing by value. The formal and actual parameters are two different variables. Manipulating the formal parameter $b has no effect on the actual parameter $j. This is demonstrated by the code execution. This passing mode is suitable for input parameters.
- Consider the swap function, which takes two formal parameters $a and $b. The function swaps the values of these two parameters. Thus, during a call to swap($i,$j), the calling code expects the values of the two actual parameters to be swapped. These are therefore output parameters (they are modified). We will therefore write:
The following script [base-13.php] shows other examples:
<?php
// types in strict mode
// declare(strict_types = 1);
// parameter switching mode
function f(&$i, $j) {
// $i will be obtained by reference
// $j will be obtained by value
$i++;
$j++;
print "f[i,j]=[$i,$j]\n";
}
function g(int &$i, int $j) : void {
// $i will be obtained by reference
// $j will be obtained by value
$i++;
$j++;
print "g[i,j]=[$i,$j]\n";
}
// tests
$i = 0;
$j = 0;
// $i and $j are passed to function f
f($i, $j);
print "test[i,j]=[$i,$j]\n";
// $i and $j are passed to function g
g($i, $j);
print "test[i,j]=[$i,$j]\n";
// pass incorrect parameters to f
$a=5.3;
$b=6.2;
f($a, $b);
print "test[a,b]=[$a,$b]\n";
// pass incorrect parameters to f
$a=5.3;
$b=6.2;
g($a, $b);
print "test[a,b]=[$a,$b]\n";
Comments
- lines 8–14: the f function discussed in the previous section, but the parameters are not typed;
- lines 16–22: the function g does the same thing as the function f, but we specify the type of the expected parameters—this is a new feature in PHP 7. We expect two parameters of type int. We want to see what happens when the actual parameter passed to the function does not have the type expected by the function;
- lines 25–26: $i and $j are two integers;
- lines 28–29: call to the function f with parameters of the expected type;
- lines 31–32: call to function g with parameters of the expected type;
- lines 34–35: the variables $a and $b are of type float;
- lines 36-37: call to function f with parameters that are not of the expected type;
- lines 41-42: call to function g with parameters that are not of the expected type;
Results
- Lines 5–6 show that the function f accepted both float parameters and worked with them;
- Lines 7–8 show that the function `g` accepted both parameters of type `float` but converted them to type `int` (line 7);
Now let’s uncomment line 4:
This instruction specifies that the types of the formal parameters must be respected. If this is not the case, an error is reported. The results of the execution then become:
- Lines 9–10: The PHP 7 interpreter threw an exception to indicate that the first parameter passed to the `g` function was of the wrong type. It is recommended to be strict about parameter types whenever possible to detect function call errors;
3.8.2. Results returned by a function
The [base-15.php] script is as follows:
<?php
// types in strict mode
declare(strict_types=1);
// results rendered by a function
// a function can return several values in an array
list($res1, $res2, $res3) = f1(10);
print "[$res1,$res2,$res3]\n";
$res = f1(10);
for ($i = 0; $i < count($res); $i++) {
print "f1 : res[$i]=$res[$i]\n";
}
// a function can render an object
$res = f2(10);
print "f2 : [$res->res1,$res->res2,$res->res3]\n";
// what kind of object?
print "nature de l'objet : ";
var_dump($res);
print "\n";
// we do the same with the f3 function
$res = f3(10);
print "f3 : [$res->res1,$res->res2,$res->res3]\n";
// what kind of object?
print "nature de l'objet : ";
var_dump($res);
print "\n";
// end
exit;
// function f1
function f1(int $valeur): array {
// returns an array ($valeur+1,$valeur+2,$valeur+3)
return array($valeur + 1, $valeur + 2, $valeur + 3);
}
// function f2
function f2(int $valeur): object {
// renders an object ($valeur+1,$valeur+2,$valeur+3)
$res->res1 = $valeur + 1;
$res->res2 = $valeur + 2;
$res->res3 = $valeur + 3;
// makes the object
return $res;
}
// function f3 - does the same thing as function f2
function f3(int $valeur): object {
// renders an object ($valeur+1,$valeur+2,$valeur+3)
$res = new stdclass();
$res->res1 = $valeur + 1;
$res->res2 = $valeur + 2;
$res->res3 = $valeur + 3;
// makes the object
return $res;
}
Results
[11,12,13]
f1 : res[0]=11
f1 : res[1]=12
f1 : res[2]=13
Warning: Creating default object from empty value in C:\Data\st-2019\dev\php7\php5-exemples\exemples\bases\base-15.php on line 43
f2 : [11,12,13]
nature de l'objet : object(stdClass)#1 (3) {
["res1"]=>
int(11)
["res2"]=>
int(12)
["res3"]=>
int(13)
}
f3 : [11,12,13]
nature de l'objet : object(stdClass)#2 (3) {
["res1"]=>
int(11)
["res2"]=>
int(12)
["res3"]=>
int(13)
}
Comments
- The previous program shows that a PHP function can return a set of results rather than a single one, in the form of an array or an object. The concept of an object is explained in more detail below;
- lines 35–38: the function f1 returns multiple values in the form of an array;
- lines 41–48: the function f2 returns multiple values in the form of an object;
- lines 51–59: the function f3 is identical to the function f2 except that it explicitly creates an object on line 53;
- Line 6 of the results displays a warning indicating that PHP was forced to create a default object on line 43 of the code, i.e., when using the notation [$res→res1]. The var_dump function on line 20 of the code reveals the object’s type and its contents. In the results, we see that:
- line 8: the default object is of type stdClass;
- lines 9–10: the res1 property is of type integer and has the value 11;
- etc…
- To avoid the warning on line 6 of the results, we explicitly create, on line 53 of the f3 function, an object of type stdClass;
3.9. Text files
The [bases-16.php] script is as follows:
<?php
// strict adherence to function parameter types
declare (strict_types=1);
// sequential operation of a text file
// this is a set of lines of the form login:pwd:uid:gid:infos:dir:shell
// each line is put into a dictionary in the form login => uid:gid:infos:dir:shell
// set the file name
$INFOS = "infos.txt";
// we open it in creation
if (!$fic = fopen($INFOS, "w")) {
print "Erreur d'ouverture du fichier $INFOS en écriture\n";
exit;
}
// generate arbitrary content
for ($i = 0; $i < 100; $i++) {
fputs($fic, "login$i:pwd$i:uid$i:gid$i:infos$i:dir$i:shell$i\n");
}
// close the file
fclose($fic);
// we use it - fgets keeps the end-of-line marker
// this prevents the retrieval of an empty string when reading a blank line
// open it for reading
if (!$fic = fopen($INFOS, "r")) {
print "Erreur d'ouverture du fichier $INFOS en lecture\n";
exit;
}
// lines are less than 1000 characters long
// line reading stops at the end-of-line mark
// or the end-of-file
while ($ligne = fgets($fic, 1000)) {
// delete the end-of-line marker if it exists
$ligne = cutNewLineChar($ligne);
// put the line in a table
$infos = explode(":", $ligne);
// retrieve login
$login = array_shift($infos);
// we neglect the pwd
array_shift($infos);
// create a dictionary entry
$dico[$login] = $infos;
}
// close it
fclose($fic);
// using the dictionary
afficheInfos($dico, "login10");
afficheInfos($dico, "X");
// end
exit;
// --------------------------------------------------------------------------
function afficheInfos(array $dico, string $clé): void {
// displays the value associated with key in the $dico dictionary if it exists
if (isset($dico[$clé])) {
// value exists - is it a painting?
$valeur = $dico[$clé];
if (is_array($valeur)) {
print "[$clé," . join(":", $valeur) . "]\n";
} else {
// $valeur is not an array
print "[$clé,$valeur]\n";
}
} else {
// $clé is not a key in the $dico dictionary
print "la clé [$clé] n'existe pas\n";
}
}
// --------------------------------------------------------------------------
function cutNewLinechar(string $ligne): string {
// delete the end-of-line mark from $ligne if it exists
$L = strlen($ligne); // line length
while (substr($ligne, $L - 1, 1) == "\n" or substr($ligne, $L - 1, 1) == "\r") {
$ligne = substr($ligne, 0, $L - 1);
$L--;
}
// end
return($ligne);
}
The infos.txt file:
The results:
[login10,uid10:gid10:infos10:dir10:shell10]
la clé [X] n'existe pas
Comments
- Line 12: fopen(filename, "w") opens the file filename for writing (w=write). If the file does not exist, it is created. If it exists, it is cleared. If creation fails, fopen returns false. In the statement if (!$fic = fopen($INFOS, "w")) {…}, there are two successive operations: 1) $fic=fopen(..) 2) if( ! $fic) {…} ;
- line 18: fputs($fic,$string) writes string to the file $fic. $string is written with the newline character \n at the end;
- line 21: fclose($fic) closes the $fic file;
- line 26: fopen(filename,"r") opens the file filename for reading (r=read). If opening fails (the file does not exist, for example), fopen returns false;
- line 34: fgets($fic,1000) reads the next line of the file, limited to 1000 characters. In the while loop ($line = fgets($fic, 1000)) {…}, there are two successive operations: 1) $line = fgets(…) 2) while ( ! $line). After the last character of the file has been read, the fgets function returns false and the while loop stops. Here, the fgets function attempts to read up to 1000 characters but stops as soon as it encounters an end-of-line character. Since all lines here have fewer than 1000 characters, [fgets] reads a line of text, including the end-of-line character. The cutNewLineChar function in lines 75–84 removes any end-of-line characters;
- line 77: the strlen($string) function returns the number of characters in $string;
- line 78: the function substr($line, $position, $size) returns $size characters from $line, starting from character #$position, where the first character is #0. On Windows machines, the end-of-line character is "\r\n". On Unix machines, it is the string "\n";
- line 40: the function array_shift($array) removes the first element from $array and returns it as the result. Here, we ignore the result returned by array_shift;
- Line 62: The is_array($variable) function returns true if $variable is an array, false otherwise;
- line 63: the join function does the same thing as the implode function we saw earlier;
3.10. JSON Encoding/Decoding

JSON (JavaScript Object Notation) encoding/decoding is something we will use extensively in the exercise that serves as the central theme of this document. The scripts [json-01.php, json-02.php, json-03.php] explain what you need to know for the rest of the document.
The script [json-01.php] is as follows:
<?php
$array1 = ["nom" => "séléné", "prénom" => "bénédicte", "âge" => 34];
// json encoding of array1 with escaped Unicode characters
print "encodage json du tableau array1 avec caractères Unicode échappés\n";
$json1 = json_encode($array1);
print "json1=$json1\n";
// json encoding of array1 with unescaped Unicode characters
print "encodage json du tableau array1 avec caractères Unicode non échappés\n";
$json2 = json_encode($array1, JSON_UNESCAPED_UNICODE);
print "json2=$json2\n";
// decoding jSON in associative array
print "décodage jSON de json2 dans tableau associatif\n";
$array2 = json_decode($json2, true);
var_dump($array2);
foreach ($array2 as $key => $value) {
print "$key:$value\n";
}
// decoding jSON in object
print "décodage jSON de json2 dans objet stdClass\n";
$array2 = json_decode($json2);
var_dump($array2);
print "prénom=$array2->prénom\n";
print "nom=$array2->nom\n";
print "âge=$array2->âge\n";
Results
Comments
- Line 6 of the code: the [json_encode] function converts its parameter into a JSON string;
- Line 2 of the results: the generated JSON string. The Unicode characters éâ have been replaced by their Unicode codes, which begin with \u;
- line 10 of the code: we do the same thing, but this time we ask that the Unicode characters be preserved as-is;
- line 4 of the results: the resulting JSON string. It is much more readable;
- Lines 14–18 of the code: We perform the reverse operation. We convert a JSON string into an associative array;
- lines 6–13 of the results: we see that we have retrieved an associative array;
- lines 19–25 of the code: we convert a JSON string into an object of type [stdClass];
- lines 18–25 of the results: we see that we have retrieved an object of type [stdClass];
- lines 23–25 of the code: the attribute A of an object O is denoted [O→A];
We can encode multi-level arrays in JSON, as shown in the following [json-02.php] script:
<?php
$array = ["nom" => "séléné", "prénom" => "bénédicte", "âge" => 34,
"mari" => ["nom" => "icariù", "prénom" => "ignacio", "âge" => 35],
"enfants" => [
["prénom" => "angèle", "age" => 8],
["prénom" => "andré", "age" => 2],
]];
// encoding jSON of the multi-level array
print "encodage jSON d'un tableau à plusieurs niveaux\n";
$json = json_encode($array, JSON_UNESCAPED_UNICODE);
print "json=$json\n";
Results
encodage jSON d'un tableau à plusieurs niveaux
json={"nom":"séléné","prénom":"bénédicte","âge":34,"mari":{"nom":"icariù","prénom":"ignacio","âge":35},"enfants":[{"prénom":"angèle","age":8},{"prénom":"andré","age":2}]}
Comments
In the JSON string:
- non-associative arrays are enclosed in square brackets [] ;
- associative arrays are enclosed in curly braces {};
The script [json-03.php] shows how to process the following JSON file [family.json]:
{
"épouse": {
"nom": "séléné",
"prénom": "bénédicte",
"âge": 34
},
"mari": {
"nom": "icariù",
"prénom": "ignacio",
"âge": 35
},
"enfants": [
{
"prénom": "angèle",
"age": 8
},
{
"prénom": "andré",
"age": 2
}
]
}
The script [json-03.php] is as follows:
<?php
// reading the jSON file
$json = file_get_contents("famille.json");
// json object decoding
$famille1 = json_decode($json);
print "----famille1\n";
var_dump($famille1);
// json decoding in associative array
print "----famille2\n";
$famille2 = json_decode($json, true);
var_dump($famille2);
Comments
- line 4: the [file_get_contents] function reads the contents of the file named [family.json] and stores them in the variable [$json];
- The variable is then decoded into an object (lines 5–8) and an associative array (lines 9–12);
Results
----famille1
object(stdClass)#2 (3) {
["épouse"]=>
object(stdClass)#1 (3) {
["nom"]=>
string(9) "séléné"
["prénom"]=>
string(11) "bénédicte"
["âge"]=>
int(34)
}
["mari"]=>
object(stdClass)#3 (3) {
["nom"]=>
string(7) "icariù"
["prénom"]=>
string(7) "ignacio"
["âge"]=>
int(35)
}
["enfants"]=>
array(2) {
[0]=>
object(stdClass)#4 (2) {
["prénom"]=>
string(7) "angèle"
["age"]=>
int(8)
}
[1]=>
object(stdClass)#5 (2) {
["prénom"]=>
string(6) "andré"
["age"]=>
int(2)
}
}
}
----famille2
array(3) {
["épouse"]=>
array(3) {
["nom"]=>
string(9) "séléné"
["prénom"]=>
string(11) "bénédicte"
["âge"]=>
int(34)
}
["mari"]=>
array(3) {
["nom"]=>
string(7) "icariù"
["prénom"]=>
string(7) "ignacio"
["âge"]=>
int(35)
}
["enfants"]=>
array(2) {
[0]=>
array(2) {
["prénom"]=>
string(7) "angèle"
["age"]=>
int(8)
}
[1]=>
array(2) {
["prénom"]=>
string(6) "andré"
["age"]=>
int(2)
}
}
}
Comments
- lines 1–38: the object resulting from decoding the JSON file [family.json];
- lines 39-76: the associative array resulting from decoding the JSON file [family.json];