Exemple 2-2-1 «Tableau: affichage, moyenne, maximum» - Script PHP

Initiation à la programmation avec le langage PHP, §2 Structures de contrôle répétitives

Tableaux ou variables indicées
PHP array();

Considérons le cas courant où une liste de n valeurs doit être conservée en mémoire de travail sous la forme d'une variable indicée x0, x1, x2, x3, x4, ... , xn-1.

Pour déclarer que la variable x est un tableau, on utilise l'instruction $x = array(); après quoi, on peut utiliser la variable indicée $x[$i] comme une variable usuelle. Remarquer que le tableau $x[0], $x[1], ..., $x[24] comporte 25 éléments.

Attention: les « HTML <table> », couramment nommées tableaux, ne doivent pas être confondues avec les tableaux « PHP array(); » introduits ici.

Le bouton permet d'exécuter le script PHP.

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport"
	content="width=device-width, initial-scale=1.0">
<meta name="robots" content="NoIndex,NoFollow">
<title>Tableau: affichage, moyenne, maximum</title>
<style>
table, td, th { border: 1px solid black; }
table { border-collapse: collapse; }
td { text-align:right; }
</style>
</head>
<body>
<?php
/*
	Initialisations
*/
$n = 25;
$x=array();
for ($i=0; $i<$n; $i++) {
	$x[$i]=random_int(0, 999);
}
/*
	Affichage
*/
echo '<table>';
for ($i=0; $i < $n; $i++) {
	echo 	'<tr><td>'
			.$i
			.'</td><td>'
			.$x[$i]
			.'</td></tr>';
}
echo '</table>';
/*
	Moyenne
*/
$s=0;
for ($i=0; $i < $n; $i++) {
	$s = $s + $x[$i];
}
if ($n > 0) {
	$m = $s/$n;
} else {
	$m = NULL;
}
echo '<p>Moyenne arithmétique = '
	.$m
	.'</p>';
/*
	Maximum
*/
if ($n > 0 ){
	$max=$x[0];
	for ($i=1; $i < $n; $i++) {
		if ($max < $x[$i]) {
			$max = $x[$i];
		}
	}
} else {
	$max = NULL;
}
echo '<p>Maximum = '
	.$max
	.'</p>';
?>
</body>
</html>

Contact |  Accueil   >   PHP   >   Initiation