🏠 Accueil ◀️ TP Précédent TP Suivant ▶️

TP7C - Tableaux en PHP

Manipulation de tableaux indexés et associatifs

🎯 Types de tableaux en PHP

1. Tableaux indexés: $couleurs = ["rouge", "vert", "bleu"];

2. Tableaux associatifs: $etudiant = ["nom" => "Kacper Momot", "age" => 18];

3. Tableaux multidimensionnels: $etudiants = [ ["nom" => "Alice"], ["nom" => "Bob"] ];

1. Tableaux indexés

Code PHP:
$competences = ["HTML5", "CSS3", "JavaScript", "PHP", "JSON"];
echo count($competences); // Affiche: 5
echo $competences[0]; // Affiche: HTML5

2. Tableaux associatifs

Code PHP:
$etudiant = [
  "nom" => "Kacper Momot",
  "age" => 18,
  "formation" => "Licence Cyber"
];
echo $etudiant["nom"]; // Affiche: Kacper Momot

3. Tableaux multidimensionnels

Code PHP:
$etudiants = [
  ["nom" => "Kacper", "age" => 20],
  ["nom" => "Alice", "age" => 22]
];
echo $etudiants[0]["nom"]; // Affiche: Kacper
ID Nom Âge Formation Notes Moyenne

4. Manipulation de tableaux

Fonctions PHP utiles:
sort($tableau) // Trie croissant
rsort($tableau) // Trie décroissant
shuffle($tableau) // Mélange
array_sum($tableau) // Somme
count($tableau) // Nombre d'éléments
PHP
<?php
// 1. Tableau indexé
$fruits = ["pomme", "banane", "orange"];
echo $fruits[0]; // "pomme"

// 2. Tableau associatif
$personne = [
    "nom" => "Kacper",
    "age" => 20
];
echo $personne["nom"]; // "Kacper"

// 3. Tableau multidimensionnel
$etudiants = [
    ["nom" => "Alice", "age" => 22],
    ["nom" => "Bob", "age" => 21]
];

// 4. Manipulations
$nombres = [5, 3, 8, 1];
sort($nombres); // Tri: [1, 3, 5, 8]
echo count($nombres); // 4
echo array_sum($nombres); // 17

// 5. Boucle sur tableau
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>