Tableaux associatifs en PHP – Exercices BTS
Niveau : BTS Informatique
Module : Gestion des bases de données pour le web
Chapitre : Structures de données
Exercice 1 : Tableau associatif simple
Créer un tableau associatif $etudiant contenant :
nom, prénom, âge et filière.
Afficher les informations.
<?php
$etudiant = [
"nom" => "Benali",
"prenom" => "Amine",
"age" => 20,
"filiere" => "Informatique"
];
echo "Nom : " . $etudiant["nom"] . "<br>";
echo "Prénom : " . $etudiant["prenom"] . "<br>";
echo "Âge : " . $etudiant["age"] . "<br>";
echo "Filière : " . $etudiant["filiere"];
?>
Exercice 2 : Parcours avec foreach
Afficher toutes les informations du tableau $etudiant
en utilisant une boucle foreach.
<?php
foreach ($etudiant as $cle => $valeur) {
echo $cle . " : " . $valeur . "<br>";
}
?>
Exercice 3 : Notes d’un étudiant
Créer un tableau associatif $notes (maths, php, réseaux),
afficher les notes puis calculer la moyenne.
<?php
$notes = [
"maths" => 14,
"php" => 16,
"reseaux" => 12
];
$somme = 0;
foreach ($notes as $matiere => $note) {
echo "Note en $matiere : $note <br>";
$somme += $note;
}
$moyenne = $somme / count($notes);
echo "Moyenne : " . $moyenne;
?>
Exercice 4 : Modification du tableau
Modifier la note de PHP, ajouter Anglais et supprimer Réseaux.
<?php
$notes["php"] = 18;
$notes["anglais"] = 15;
unset($notes["reseaux"]);
foreach ($notes as $matiere => $note) {
echo "$matiere : $note <br>";
}
?>
Exercice 5 : Condition (Admission)
Afficher Admis si la moyenne ≥ 10, sinon Ajourné.
<?php
$moyenne = array_sum($notes) / count($notes);
if ($moyenne >= 10) {
echo "Résultat : Admis";
} else {
echo "Résultat : Ajourné";
}
?>
Exercice de synthèse – Type examen BTS
Créer un tableau d’étudiants et afficher ceux qui sont admis.
<?php
$classe = [
["nom" => "Ali", "note" => 12],
["nom" => "Sara", "note" => 9],
["nom" => "Yacine", "note" => 15]
];
foreach ($classe as $etudiant) {
if ($etudiant["note"] >= 10) {
echo $etudiant["nom"] . " est admis<br>";
}
}
?>
