1ère Générale NSI

 

Term. Générale NSI

 

Terminale STI2D SIN

Bts Ccst

Technico-commercial 3.0

[[{"text":"\"PHP","title":"PHP"},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

1. Qu'est ce que PHP ?


Le PHP, acronyme récursif pour PHP Hypertext Preprocessor est un langage de scripts spécialement conçu pour le développement d'applications web.
Il peut être intégré facilement au HTML.

Le langage PHP a été créé en 1994 par Rasmus Lerdorf, un programmeur groenlandais et canadien pour son site web personnel.

Un exemple de code PHP

On petit exemple en PHP qui

  • Calcule la somme de deux varariables, $var1=5 et  $var2=7 ;
  • Affiche la somme avec la fonction avec la fonction echo ;
  • Calcule et affiche la somme de deux entiers choisis aléatoirement entre 1 et 100, avec la fonction rand(1 , 100).
<!doctype html>\n<html>\n <head>\n  <title>\n   Exemple de variables\n  </title>\n  <meta charset=\"utf-8\"/>\n </head>\n <body>\n <h1> Un premier programme en PHP : pour les tests</h1>\n \n <?php\n  // Commentaires en php\t\n  // Utilisation de variables, avec le dollard $\n        $var1=5;\n        $var2=7;\n\t$somme=$var1+$var2;\n\t\t\n\t// echo permet d'afficher sur la page\n\t// On peut méler du texte et des variables \n\techo \"<p>La somme de $var1 et $var2 est $somme.</p>\";\t\t\n\t\t\n\t$nombre1=rand(1,100); // rand(a,b) génère un entier aléatoire entre a et b (inclus)\n\t\t\n\techo \"<p>Le 1er nombre choisi au hasard est $nombre1.</p>\";\n\t$nombre2=rand(1,100);\n\techo \"<p>Le 2e nombre choisi au hasard est $nombre2.</p>\";\n\t\t\n\t$somme=$nombre1+$nombre2;\n\t// On affiche la somme\n\techo \"<p>La somme de $nombre1 et $nombre2 est $somme.</p>\";\t\n ?>\n</body>\n</html>\n

 

  • Visualiser le résultat
    Un lien vers le fichier hébergé sur un serveur distant : PHP-Exemple1.php.
     

Premières remarques sur le PHP

  • L'affichage en PHP utilise la fonction echo \" texte et $variables \".
    On peut afficher du texte et des variables $var simultanément très simplement.
  • Les lignes se terminent par un point virgule  ;.
  • Les variables se définissent avec le dollard  $var1  et peuvent s'intégrer facilement au texte.

Petit exercice important

  1. Affichez le code source (Click droit) de la page PHP-Exemple1.php.
  2. Vous remarquez que le code source propose juste l'affichage, sans les lignes de code PHP.
  3. Actualisez la page, on voit que le contenu change car la fonction rand(1 , 100) est appelée.
  4. C'est magique, le client, c'est à dire notre ordinateur ne s'aperçoit pas qu'il y a un calcul d'effectué.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Un fonctionnement distant

  • Le PHP fonctionne en fait sur serveur distant.
    On ne peut pas avoir un fonctionnement immédiat sur notre disque comme avec le HTML, le CSS ou le JavaScript.
      
  • Ce qui distingue PHP des langages de script comme le Javascript, est que le code est exécuté sur le serveur, générant ainsi le HTML, qui sera ensuite envoyé au client. Le client ne reçoit que le résultat du script, sans aucun moyen d'avoir accès au code qui a produit ce résultat. Vous pouvez configurer votre serveur web afin qu'il analyse tous vos fichiers HTML comme des fichiers PHP. Ainsi, il n'y a aucun moyen de distinguer les pages qui sont produites dynamiquement des pages statiques.
     
  • le serveur doit donc être capable de repérer les parties de codes PHP, cela se fera grâce à des balises.
    Le code PHP est donc inclus entre une balise de début  <?php  et une balise de fin  ?>  qui permettent au serveur web de passer en mode PHP, ce que ne fait pas votre navigateur sur votre disque dur.

 \"client

Le fonctionnement du PHP

Vous pouvez maintenant tranquillement lire cette page qui expose le fonctionnement du PHP.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

2. Préparez votre environnement de travail


Il va donc nous falloir préparer un environement de travail afin de pouvoir lire les fichiers PHP.

Plusieurs solutions sont possibles, si vous avez déjà un site en ligne, tout sera plus facile, sinon, vous allez devoir installer plusieurs émulateurs de serveurs distants.

Cas 1 : j'ai un site en ligne

  • Si vous avez un site en ligne, tout est très simple, il vous suffit d'envoyer vos fichiers sur votre espace et de les ouvrir via votre navigateur. Chaque site à un interpréteur PHP.
  • Pour télécharger facilement vos fichiers, vous pouvez : 
    • Soit vous connecter chez votre hébergeur ;
    • Soit utiliser un client FTP. Je vous conseil d'installer FileZilla, gratuit et très simple d'utilisation. 
      Il vous faudra cependant récuprérer chez votre hébergeur vos identifiants de connexion. C'est un peu long la première fois mais ensuite c'est très rapide.

\"filezilla

Cas 2 : je veux installer un serveur en local

Deux principaux serveurs sont utilisés : 

Vous pouvez consulter le tutoriel d'Openclassrooms.

Quelques remarques post Installation

  •  Il ne suffit pas d'ouvrir un fichier avec son navigateur pour que cela fonctionne, on doit généralement lancer l'émulateur puis tapper dans son navigateur :

http://localhost/MonFichier.php

  • WampServeur
    • Création automatique d’un répertoire « www » lors de l’installation (typiquement c:\\wamp\\www).
    • Créez un sous répertoire pour votre projet et déposez-y vos fichiers PHP
    • Cliquez sur le lien « Localhost » du menu de WampServer ou ouvrez votre navigateur à l’adresse :

http://localhost/MonFichier.php

    • Bases de données.
      Au lancement de PhpMyAdmin, il vous sera demandé un nom utilisateur et un mot de passe.
      Après installation de Wampserver 3,
      • le nom utilisateur par défaut est \"root\" (Sans les guillemets)
      • et il n'y a pas de mot de passe, ce qui veut dire que vous devez laisser la case Mot de passe du formulaire d'accès vide.
         
  • Xampp
    • Placer les projets dans le dossier htdocs qui est dans C:\\xampp\\htdocs
    • Pour ouvrir un fichier nommé MonFichier.php qui est dans le répertoire htdocs, tapper dans votre navigateur :

http://localhost/MonFichier.php

    • Bases de données.
      Pour accéder à la base de données
      => Admin Mysql

 

Vous utiliserez le vps dont l'adresse ip sera donné par votre professeur.

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

3. Un test puis les exercices et travaux pratiques


Nous sommes prêts pour un petit test.

  • Recopier le code source de l'exemple 1, enregistrez-le sur votre disque dur avec l'extension .php et ouvrez-le dans votre navigateur .... suspens !

 

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

4. Programmer en PHP

Quelques remarques sur les fonctions, les structures conditionnels en PHP

    • Les fonctions en PHP fonctionnent comme en Javascript. Le mot clé function permet de définir une fonction.
    • Les paramètres sont écrits entre parenthèses précédés du symbole $ comme toute les variables.
    • Le mot clé return permet de renvoyer une valeur.
    • Il existe de nombreuses fonctions intégrées en PHP vous pouvez consulter ces sites de références au fur et à mesure des besoins.
    • De même les structures conditionnelles if et if else fonctionnent comment en Javascript.
       
    • Par exemple cette fonction renvoie le maximum des deux nombres
<?php\n  function maximum($a,$b)\n{\nif ($a>$b)\n    return $a;\nelse \n    return $b;\n}\n?>\n  \n

 

  • De même les structures itératives, les boucles for et while fonctionnent comment en Javascript.


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Un exemple

L'exemple ci-dessous se sert d'une boucle for pour afficher un tableau à l'écran avec une boucles for et une boucle while . C'est magique.

<head>\n  <title>\n   PHP - Exemple 2\n  </title>\n  <meta charset=\"utf-8\"/>\n </head>\n <body>\n <h1> PHP - Exemple 2 </h1>\n <table border=\"1\">\n  <tr>\n   <?php\n   for($i=1;$i<=10;$i=$i+1) // ou ($i=1;$i<=10;$i++)\n   {\n    echo \"<td>$i</td>\";\n   }\n   ?>\n  </tr>\n </table>\n \n <p> </p>\n \n <table border=\"2\">\n  <tr>\n   <?php\n   $i = 1;\n   while ($i <= 10) \n   {\n    echo \"<td>$i</td>\";\n\t$i=$i+1;\n\t}\n   ?>\n  </tr>\n </table>\n \n</body>\n</html>\n

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Exercice 1
La fonction rand(a,b) renvoie un entier aléatoire compris entre a et b.
1. Ecrire un script qui choisit aléatoirement un nombre entre 1 et 15.
2. Et qui affiche le table de multiplication de ce nombre dans un tableau.
Toute amélioration est la bienvenue.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Exercice 2
La fonction rand(a,b) renvoie un entier aléatoire compris entre a et b.
Ecrire un script en php qui :
1. choisit 100 nombres aléatoires entre 0 et 100 ;
2. les affiche  ;
3. et affiche leur moyenne.
Toute amélioration est la bienvenue.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

5. Interagir avec une page en PHP : les méthodes GET et POST

Un script PHP s'exécute sur le serveur lorsque l'utilisateur accède à un fichier par un lien. Ce script effectue un certain nombre d'instructions pour produire la page web demandée et s'arrête lorsque celle-ci est produite.
Comment faisons-nous pour passer une information d'une page à l'autre ? De l'utilisateur à la page .PHP ?

Par exemple, si je saisi mon compte utilisateur sur un site et qu'en cliquant je suis conduis vers la page de mon compte, comment cette page se souvient-elle du nom que j'ai écrit dans la page précédente ?

Il existe plusieurs solutions pour transmettre des informations d'une page aux autres :

  • Cookies ;
  • base de données ;
  • fichiers textes ;
  • la méthode  GET ;
  • la méthode POST.

Nous allons étudier les méthodes GET et POST.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

5a. La méthode GET
Interagir avec une page en PHP avec la méthode GET

 

Les variables ne transitent pas toujours via un formulaire mais bien souvent par l'URL via la méthode GET.

L'URL (Uniform Resource Locator) sert à représenter une adresse sur le web comme celle du site www.math93.com.

Par exemple, après avoir fait une recherche sur Google, par exemple avec math93, la barre d'adresse contient une URL longue qui ressemble à ceci :

\"recherche

Dans cet exemple, les informations après le point d'interrogation sont des données que l'on fait transiter d'une page à une autre.


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

5a1. Former une URL pour envoyer des paramètres

Imaginons que votre site s'appelle math93.com et que vous avez une page PHP intitulée bonjour.php. Pour accéder à cette page, vous devez aller à l'URL suivante :

http://www.math93.com/bonjour.php

Pour envoyer des informations à la page bonjour.php, on va ajouter des informations à la fin de l'URL, comme ceci :

\"php

  • On écrit les variables et les valeurs des variables après un point d'intérogation ? .
  • On sépare les variables par le symbole & .
  • La seule limite est la longueur de l'URL. En général il n'est pas conseillé de dépasser les 256 caractères.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

5a2. Récupérer les valeurs des variables

Nous avons fait un lien vers le fichier php bonjour.php et à deux variables nom et prenom.

bonjour.php?nom=Galois&prenom=Evariste

Pour récupérer les valeurs des variables, on y accède via la variable $_GET.

  • $_GET['nom'] .     à la valeur Galois ;  
  • $_GET['prenom'] .  à la valeur Evariste ;

 

Par exemple on a ici avec le petit code en écrivant dant la console :

Essayer de changer les noms et prénoms dans l'adresse URL.

 

<head>\n  <title>\n   PHP - Exemple 3\n  </title>\n  <meta charset=\"utf-8\"/>\n </head>\n <body>\n <h1> PHP - Exemple 3 </h1>\n <?php \n // les variables existent-t-elles ?\n if(isset($_GET['nom']) and isset($_GET['prenom']))\n {// oui les variables existent \n    $lenom=$_GET['nom'];\n    $leprenom=$_GET['prenom'];\n    //echo \"<p>Bonjour $_GET['prenom'] et $_GET['nom'] !</p>\" ;\n    echo \"<p>Bonjour $leprenom   $lenom</p>\" ;\n }\n else\n {\n    echo \"<p>Bonjour Madame ou Monsieur.</p>\" ;\n }\n ?> \n</body>\n</html>\n

 

  • Remarque :  isset(var)   - Détermine si la variable var est déclarée et est différente de NULL.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Exercice 3
1. Ecrire une page qui prend deux nombres dans l'URL et affiche leur somme.
2. Modifier la page pour donner trois paramètres dans l'URL, deux nombres et une opération. Le résultat de l'opération sera affiché dans la page.
Toute amélioration est la bienvenue.

 

Exercice 4
1. Ecrire deux pages, la première choisissant un nombre au hasard entre -10 et 10
2. et contenant un lien vers la seconde qui affichera la racine carrée du nombre choisi, si cela est possible.
Toute amélioration est la bienvenue.

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

5b. La méthode POST
Interagir avec une page en PHP avec la méthode POST

Il existe une autre méthode pour passer des données d'une page à l'autre sans mentionner les valeurs dans l'URL.

Il s'agit de la méthode utilisée dans les formulaires

Un exemple

Reprenons l'exemple 3 avec le nom et le prénom.

  1. On va donc écrire deux pages, la première une page HTML que l'on va nommer ex4-HTML.html, et la deuxième une page PHP l'on va nommer ex4-PHP.php
  2. Afin de pouvoir accéder aux contenus envoyés par la méthode POST, il faut donner à chaque élément dont on veut récuperer les valeurs l'attribut name   .
  3. Pour récupérer les valeurs des variables, on y accède via la variable $_POST.
  • $_POST['nom'] .     à la valeur du nom entré ;   
  • $_POST['prenom'] .  à la valeur du prénom entré ;

 

<!doctype html>\n<html>\n<head>\n  <title>\n   PHP - Exemple 4 - Méthode POST Fichier HTML\n  </title>\n  <meta charset=\"utf-8\"/>\n </head>\n <body>\n <h1> PHP - Exemple 4 - Méthode POST Fichier HTML</h1>\n  <form action=\"ex4-PHP.php\" method=\"post\">\n  <label for=\"nom\">Votre Nom :</label>  \n  <input type=\"text\" name=\"nom\"> \n  <div> et </div> \n  <label for=\"prenom\">Votre Prénom :</label>\n  <input type=\"text\" name=\"prenom\">\n  <input type=\"submit\" value=\"Valider\">\n  </form>\n</body>\n</html>\n

 

<!doctype html>\n<html>\n<head>\n  <title>\n   PHP - Exemple 4 - Méthode POST Fichier PHP\n  </title>\n  <meta charset=\"utf-8\"/>\n </head>\n <body>\n <h1> PHP - Exemple 4 - Méthode POST Fichier PHP </h1>\n <?php \n // les variables existent-t-elles ?\n if(isset($_POST['nom']) and isset($_POST['prenom']))\n {// oui les variables existent \n    $lenom=$_POST['nom'];\n    $leprenom=$_POST['prenom'];\n    //echo \"<p>Bonjour $_POST['prenom']   et $_POST['nom'] !</p>\" ;\n    echo \"<p>Bonjour $leprenom    $lenom</p>\" ;\n }\n else\n {\n\techo \"<p>Bonjour Madame ou Monsieur.</p>\" ;\n }\n ?> \n</body>\n

 

 


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Exercice 5
Reprendre les exercices 3 et 4 mais en utilisant la méthode POST et un formulaire.
Toute amélioration est la bienvenue.

 

Exercice 6 : un QCM
1. Ecrire deux pages, la première contenant un QCM avec au moins trois questions.
2. Les réponses seront proposées et l'utilisateur devra faire son choix par des cases à cocher.
3. La seconde page affichera le score obtenu.
Aide : Pour récupérer l'information \"case cochée, c'est assez simple : la variable n'existe dans le post que si la case a été cochée.
Toute amélioration est la bienvenue.

 

","title":" "},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is \".php\".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function \"echo\" to output the text \"Hello World!\" on a web page:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo \"Hello World!\";
?>

</body>
</html>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Comments in PHP

A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is looking at the code.

Comments can be used to:

  • Let others understand what you are doing
  • Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code

PHP supports several ways of commenting:

Example

<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.

In the example below, all three echo statements below are legal (and equal):

Example

<!DOCTYPE html>
<html>
<body>

<?php
ECHO \"Hello World!<br>\";
echo \"Hello World!<br>\";
EcHo \"Hello World!<br>\";
?>

</body>
</html>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

However; all variable names are case-sensitive.

In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables):

Example

<!DOCTYPE html>
<html>
<body>

<?php
$color = \"red\";
echo \"My car is \" . $color . \"<br>\";
echo \"My house is \" . $COLOR . \"<br>\";
echo \"My boat is \" . $coLOR . \"<br>\";
?>

</body>
</html>
Run example»
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Variables

 

Variables are \"containers\" for storing information.


Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example

<?php
$txt = \"Hello world!\";
$x = 5;
$y = 10.5;

echo $txt ;

echo $x ;
echo $y ;
?>
Run example »


After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

<?php
$txt = \"W3Schools.com\";
echo \"I love $txt!\";
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

The following example will produce the same output as the example above:

Example

<?php
$txt = \"W3Schools.com\";
echo \"I love \" . $txt . \"!\";
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

The following example will output the sum of two variables:

Example

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
Run example 
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.


PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

  • local
  • global
  • static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

Example

<?php
$x = 5; // global scope

function myTest() {
    // using x inside this function will generate an error
    echo \"<p>Variable x inside function is: $x</p>\";
}
myTest();

echo \"<p>Variable x outside function is: $x</p>\";
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

Example

<?php
function myTest() {
    $x = 5; // local scope
    echo \"<p>Variable x inside function is: $x</p>\";
}
myTest();

// using x outside the function will generate an error
echo \"<p>Variable x outside function is: $x</p>\";
?>
Run example »

You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>
Run example »

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

The example above can be rewritten like this:


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Example

<?php
$x = 5;
$y = 10;

function myTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>
Run example »","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}

myTest();
myTest();
myTest();
?>
Run example »

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP echo and print Statements

n PHP there are two basic ways to get output: echo and print.

In this tutorial we use echo (and print) in almost every example. So, this chapter contains a little more info about those two output statements.


 


The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().

Display Text

The following example shows how to output text with the echo command (notice that the text can contain HTML markup):

Example

<?php
echo \"<h2>PHP is Fun!</h2>\";
echo \"Hello world!<br>\";
echo \"I'm about to learn PHP!<br>\";
echo \"This \", \"string \", \"was \", \"made \", \"with multiple parameters.\";
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Display Variables

The following example shows how to output text and variables with the echo statement:

Example

<?php
$txt1 = \"Learn PHP\";
$txt2 = \"W3Schools.com\";
$x = 5;
$y = 4;

echo \"<h2>$txt1</h2>\";
echo \"Study PHP at $txt2<br>\";
echo $x + $y;
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Data Types

 

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

PHP String

A string is a sequence of characters, like \"Hello world!\".

A string can be any text inside quotes. You can use single or double quotes:

Example

<?php 
$x = \"Hello world!\";
$y = 'Hello world!';

echo $x;
echo \"<br>\";
echo $y;
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Rules for integers:

  • An integer must have at least one digit
  • An integer must not have a decimal point
  • An integer can be either positive or negative
  • Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)

In the following example $x is an integer. The PHP var_dump() function returns the data type and value:

Example

<?php 
$x = 5985;
var_dump($x);

?>
Run example »

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

Example

<?php 
$x = 10.365;
var_dump($x);
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing. You will learn more about conditional testing in a later chapter of this tutorial.


PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type and value:

Example

<?php 
$cars = array(\"Volvo\",\"BMW\",\"Toyota\");
var_dump($cars);
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Object

An object is a data type which stores data and information on how to process that data.

In PHP, an object must be explicitly declared.

First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods:

Example

<?php
class Car {
    function Car() {
        $this->model = \"VW\";
    }
}

// create an object
$herbie = new Car();

// show object properties
echo $herbie->model;
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example

<?php
$x = \"Hello world!\";
$x = null;
var_dump($x);
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

PHP Strings


A string is a sequence of characters, like \"Hello world!\".


PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.


Get The Length of a String

The PHP strlen() function returns the length of a string.

The example below returns the length of the string \"Hello world!\":

Example

<?php
echo strlen(\"Hello world!\"); 
?>
Run example »

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Count The Number of Words in a String

The PHP str_word_count() function counts the number of words in a string:

Example

<?php
echo str_word_count(\"Hello world!\"); 
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Reverse a String

The PHP strrev() function reverses a string:

Example

<?php
echo strrev(\"Hello world!\"); 
?>
Run example »
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Search For a Specific Text Within a String

The PHP strpos() function searches for a specific text within a string.

If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

The example below searches for the text \"world\" in the string \"Hello world!\":

Example

<?php
echo strpos(\"Hello world!\", \"world\");
?>
Run example »

Tip: The first character position in a string is 0 (not 1).

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a string.

The example below replaces the text \"world\" with \"Dolly\":

Example

<?php
echo str_replace(\"world\", \"Dolly\", \"Hello world!\"); // outputs Hello Dolly!
?>
Run example »

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

The PHP string reference contains description and example of use, for each function!


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP Constants
Constants are like variables except that once they are defined they cannot be changed or undefined.

PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant
To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive)
Parameters:

name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
Example
Create a constant with a case-sensitive name:

<?php
define(\"GREETING\", \"Welcome to W3Schools.com!\");
echo GREETING;
?>
Example
Create a constant with a case-insensitive name:

<?php
define(\"GREETING\", \"Welcome to W3Schools.com!\", true);
echo greeting;
?>
PHP Constant Arrays
In PHP7, you can create an Array constant using the define() function.

Example
Create an Array constant:

<?php
define(\"cars\", [
  \"Alfa Romeo\",
  \"BMW\",
  \"Toyota\"
]);
echo cars[0];
?>
Constants are Global
Constants are automatically global and can be used across the entire script.

Example
This example uses a constant inside a function, even if it is defined outside the function:

<?php
define(\"GREETING\", \"Welcome to W3Schools.com!\");

function myTest() {
  echo GREETING;
}
 
myTest();
?>

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP Operators
PHP Operators
Operators are used to perform operations on variables and values.

ithmetical operations, such as addition, subtraction, multiplication etc.

OperatorNameExampleResultShow it
+Addition$x + $ySum of $x and $yTry it »
-Subtraction$x - $yDifference of $x and $yTry it »
*Multiplication$x * $yProduct of $x and $yTry it »
/Division$x / $yQuotient of $x and $yTry it »
%Modulus$x % $yRemainder of $x divided by $yTry it »
**Exponentiation$x ** $yResult of raising $x to the $y'th powerTry it »





PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

.

AssignmentSame as...DescriptionShow it
x = yx = yThe left operand gets set to the value of the expression on the rightTry it »
x += yx = x + yAdditionTry it »
x -= yx = x - ySubtractionTry it »
x *= yx = x * yMultiplicationTry it »
x /= yx = x / yDivisionTry it »
x %= yx = x % yModulusTry it »

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is \"=\". It means that the left operand gets set to the value of the assignment expression on the right.

):

OperatorNameExampleResultShow it
==Equal$x == $yReturns true if $x is equal to $yTry it »
===Identical$x === $yReturns true if $x is equal to $y, and they are of the same typeTry it »
!=Not equal$x != $yReturns true if $x is not equal to $yTry it »
<>Not equal$x <> $yReturns true if $x is not equal to $yTry it »
!==Not identical$x !== $yReturns true if $x is not equal to $y, or they are not of the same typeTry it »
>Greater than$x > $yReturns true if $x is greater than $yTry it »
<Less than$x < $yReturns true if $x is less than $yTry it »
>=Greater than or equal to$x >= $yReturns true if $x is greater than or equal to $yTry it »
<=Less than or equal to$x <= $yReturns true if $x is less than or equal to $yTry it »
<=>Spaceship$x <=> $yReturns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.Try it »


PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):

.

OperatorNameDescriptionShow it
++$xPre-incrementIncrements $x by one, then returns $xTry it »
$x++Post-incrementReturns $x, then increments $x by oneTry it »
--$xPre-decrementDecrements $x by one, then returns $xTry it »
$x--Post-decrementReturns $x, then decrements $x by oneTry it »






PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator\tName\tDescription\tShow it
++$x\tPre-increment\tIncrements $x by one, then returns $x\t
$x++\tPost-increment\tReturns $x, then increments $x by one\t
--$x\tPre-decrement\tDecrements $x by one, then returns $x\t
$x--\tPost-decrement\tReturns $x, then decrements $x by one\t



PHP Logical Operators
The PHP logical operators are used to combine conditional statements.



OperatorNameExampleResultShow it
andAnd$x and $yTrue if both $x and $y are trueTry it »
orOr$x or $yTrue if either $x or $y is trueTry it »
xorXor$x xor $yTrue if either $x or $y is true, but not bothTry it »
&&And$x && $yTrue if both $x and $y are trueTry it »
||Or$x || $yTrue if either $x or $y is trueTry it »
!Not!$xTrue if $x is not trueTry it »

PHP String Operators
PHP has two operators that are specially designed for strings.


OperatorNameExampleResultShow it
.Concatenation$txt1 . $txt2Concatenation of $txt1 and $txt2Try it »
.=Concatenation assignment$txt1 .= $txt2Appends $txt2 to $txt1
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP if...else...elseif Statements
Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and another code if that condition is false
if...elseif...else statement - executes different codes for more than two conditions
switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.

Syntax
if (condition) {
  code to be executed if condition is true;
}
Example
Output \"Have a good day!\" if the current time (HOUR) is less than 20:

<?php
$t = date(\"H\");

if ($t < \"20\") {
  echo \"Have a good day!\";
}
?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.

Syntax
if (condition) {
  code to be executed if condition is true;
} else {
  code to be executed if condition is false;
}
Example
Output \"Have a good day!\" if the current time is less than 20, and \"Have a good night!\" otherwise:

<?php
$t = date(\"H\");

if ($t < \"20\") {
  echo \"Have a good day!\";
} else {
  echo \"Have a good night!\";
}
?>
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.

Syntax
if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}
Example
Output \"Have a good morning!\" if the current time is less than 10, and \"Have a good day!\" if the current time is less than 20. Otherwise it will output \"Have a good night!\":

<?php
$t = date(\"H\");

if ($t < \"10\") {
  echo \"Have a good morning!\";
} elseif ($t < \"20\") {
  echo \"Have a good day!\";
} else {
  echo \"Have a good night!\";
}
?>
PHP - The switch Statement
The switch statement will be explained in the next chapter.

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP switch Statement
The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch (n) {
  case label1:
    code to be executed if n=label1;
    break;
  case label2:
    code to be executed if n=label2;
    break;
  case label3:
    code to be executed if n=label3;
    break;
    ...
  default:
    code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

Example
<?php
$favcolor = \"red\";

switch ($favcolor) {
  case \"red\":
    echo \"Your favorite color is red!\";
    break;
  case \"blue\":
    echo \"Your favorite color is blue!\";
    break;
  case \"green\":
    echo \"Your favorite color is green!\";
    break;
  default:
    echo \"Your favorite color is neither red, blue, nor green!\";
}
?>

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP Loops
In the following chapters you will learn how to repeat code by using loops in PHP.

PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array



","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP while Loop
The while loop - Loops through a block of code as long as the specified condition is true.

The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition is true) {
  code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:

Example
<?php
$x = 1;

while($x <= 5) {
  echo \"The number is: $x <br>\";
  $x++;
}
?>
Example Explained
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:

Example
<?php
$x = 0;

while($x <= 100) {
  echo \"The number is: $x <br>\";
  $x+=10;
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100 - Continue the loop as long as $x is less than or equal to 100
$x+=10; - Increase the loop counter value by 10 for each iteration

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP do while Loop
The do...while loop - Loops through a block of code once, and then repeats the loop as long as the specified condition is true.

The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Syntax
do {
  code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Example
<?php
$x = 1;

do {
  echo \"The number is: $x <br>\";
  $x++;
} while ($x <= 5);
?>
Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means that the do...while loop will execute its statements at least once, even if the condition is false. See example below.

This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:

Example
<?php
$x = 6;

do {
  echo \"The number is: $x <br>\";
  $x++;
} while ($x <= 5);
?>


COLOR PICKER

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP for Loop
The for loop - Loops through a block of code a specified number of times.

The PHP for Loop
The for loop is used when you know in advance how many times the script should run.

Syntax
for (init counter; test counter; increment counter) {
  code to be executed for each iteration;
}
Parameters:

init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:

Example
<?php
for ($x = 0; $x <= 10; $x++) {
  echo \"The number is: $x <br>\";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 10; - Continue the loop as long as $x is less than or equal to 10
$x++ - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:

Example
<?php
for ($x = 0; $x <= 100; $x+=10) {
  echo \"The number is: $x <br>\";
}
?>
Example Explained
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100; - Continue the loop as long as $x is less than or equal to 100
$x+=10 - Increase the loop counter value by 10 for each iteration

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an array.

The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax
foreach ($array as $value) {
  code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples
The following example will output the values of the given array ($colors):

Example
<?php
$colors = array(\"red\", \"green\", \"blue\", \"yellow\");

foreach ($colors as $value) {
  echo \"$value <br>\";
}
?>
The following example will output both the keys and the values of the given array ($age):

Example
<?php
$age = array(\"Peter\"=>\"35\", \"Ben\"=>\"37\", \"Joe\"=>\"43\");

foreach($age as $x => $val) {
  echo \"$x = $val<br>\";
}
?>
You will learn more about arrays in the PHP Arrays chapter.
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP Break and Continue
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to \"jump out\" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    break;
  }
  echo \"The number is: $x <br>\";
}
?>
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    continue;
  }
  echo \"The number is: $x <br>\";
}
?>
Break and Continue in While Loop
You can also use break and continue in while loops:

Break Example
<?php
$x = 0;

while($x < 10) {
  if ($x == 4) {
    break;
  }
  echo \"The number is: $x <br>\";
  $x++;
}
?>
Continue Example
<?php
$x = 0;

while($x < 10) {
  if ($x == 4) {
    $x++;
    continue;
  }
  echo \"The number is: $x <br>\";
  $x++;
}
?>

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
PHP Functions
The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.

A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:

Syntax
function functionName() {
  code to be executed;
}
Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named \"writeMsg()\". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs \"Hello world!\". To call the function, just write its name followed by brackets ():

Example
<?php
function writeMsg() {
  echo \"Hello world!\";
}

writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example
<?php
function familyName($fname) {
  echo \"$fname Refsnes.<br>\";
}

familyName(\"Jani\");
familyName(\"Hege\");
familyName(\"Stale\");
familyName(\"Kai Jim\");
familyName(\"Borge\");
?>
The following example has a function with two arguments ($fname and $year):

Example
<?php
function familyName($fname, $year) {
  echo \"$fname Refsnes. Born in $year <br>\";
}

familyName(\"Hege\", \"1975\");
familyName(\"Stale\", \"1978\");
familyName(\"Kai Jim\", \"1983\");
?>
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a \"Fatal Error\" if the data type mismatches.

In the following example we try to send both a number and a string to the function without using strict:

Example
<?php
function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, \"5 days\");
// since strict is NOT enabled \"5 days\" is changed to int(5), and it will return 10
?>
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, \"5 days\");
// since strict is enabled and \"5 days\" is not an integer, an error will be thrown
?>
The strict declaration forces things to be used in the intended way.

PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
  echo \"The height is : $minheight <br>\";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
To let a function return a value, use the return statement:

Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
  $z = $x + $y;
  return $z;
}

echo \"5 + 10 = \" . sum(5, 10) . \"<br>\";
echo \"7 + 13 = \" . sum(7, 13) . \"<br>\";
echo \"2 + 4 = \" . sum(2, 4);
?>
PHP Return Type Declarations
PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a \"Fatal Error\" on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( { )bracket when declaring the function.

In the following example we specify the return type for the function:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
  return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
  return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Passing Arguments by Reference
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example
Use a pass-by-reference argument to update a variable:

<?php
function add_five(&$value) {
  $value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"Sources : 
https://www.w3schools.com/
https://www.math93.com/lycee/nsi-1ere/nsi-1ere/
","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}]]

En poursuivant votre navigation sur mon site, vous acceptez l’utilisation des Cookies et autres traceurs  pour réaliser des statistiques de visites et enregistrer sur votre machine vos activités pédagogiques. En savoir plus.