Skip to content

Instantly share code, notes, and snippets.

@alexsoyes
Last active September 18, 2021 10:58
Show Gist options
  • Save alexsoyes/7668375857c1a34540f49260f3b7b17d to your computer and use it in GitHub Desktop.
Save alexsoyes/7668375857c1a34540f49260f3b7b17d to your computer and use it in GitHub Desktop.
Cours PHP : Boucle "foreach"
<?php
$students = [
[
'firstname' => 'Alex',
'age' => 27,
],
[
'firstname' => 'Bastien',
'age' => 19,
],
[
'firstname' => 'Carolina',
'age' => 47,
],
];
// pas besoin de count() avec le foreach !
foreach ($students as $student) {
printf("L'étudiant %s a %d ans !", $student['firstname'], $student['age']);
}
/**
* La clef $key contient l'index (de 0 à 2)
* La valeur $value contient la valeur de l'index, soit $students[0], puis $students[1] jusqu'à $students[2]
*/
foreach ($students as $key => $value) {
printf("L'étudiant %s a %d ans !\n", $students[$key]['firstname'], $students[$key]['age']);
printf("L'étudiant %s a %d ans !\n", $value['firstname'], $value['age']);
}
// foreach peut parcourir un tableau simple ou un tableau clef/valeur !
foreach (['Ben', 'Tom', 'Liz'] as $sibling) {
printf("J'ai un frère ou une soeur qui s'appelle $sibling !\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment