Last active
September 18, 2021 10:58
-
-
Save alexsoyes/7668375857c1a34540f49260f3b7b17d to your computer and use it in GitHub Desktop.
Cours PHP : Boucle "foreach"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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