EXERCICES :
01-Trouver le plus grand et le plus petit nombre dans un tableau
<?php
$tab = [10, 20, 30, 40, 50];
$max = $tab[0];
$min = $tab[0];
foreach ($tab as $element) {
if ($element > $max) {
$max = $element;
}
if ($element < $min) {
$min = $element;
}
}
echo "Le plus grand nombre dans le tableau est : " . $max . "\n";
echo "Le plus petit nombre dans le tableau est : " . $min;
?>
3.Inverser un tableau
- Écrire un programme qui inverse l'ordre des éléments d'un tableau [1, 2, 3, 4, 5] en utilisant une boucle for.
<?php
$tab = [1, 2, 3, 4, 5];
$inverted = [];
for ($i = count($tab) - 1; $i >= 0; $i--) {
$inverted[] = $tab[$i];
}
print_r($inverted);
?>
4. Afficher les nombres premiers de 1 à 50
<?php
for ($i = 2; $i <= 50; $i++) {
$est_premier = true;
for ($j = 2; $j <= sqrt($i); $j++) {
if ($i % $j == 0) {
$est_premier = false;
break;
}
}
if ($est_premier) {
echo $i . " ";
}
}
?>
5.Trouver l'index du plus grand nombre dans un tableau
<?php
$tab = [10, 20, 30, 40, 50];
$max = $tab[0];
$index = 0;
for ($i = 1; $i < count($tab); $i++) {
if ($tab[$i] > $max) {
$max = $tab[$i];
$index = $i;
}
}
echo "L'index du plus grand nombre dans le tableau est : " . $index;
?>
6.Afficher les éléments d'un tableau en ordre croissant
<?php
$tab = [5, 3, 8, 1, 2];
for ($i = 0; $i < count($tab); $i++) {
for ($j = $i + 1; $j < count($tab); $j++) {
if ($tab[$i] > $tab[$j]) {
$temp = $tab[$i];
$tab[$i] = $tab[$j];
$tab[$j] = $temp;
}
}
}
print_r($tab);
?>
7.Créez un tableau associatif contenant les noms et les prix de deux produits et affichez-les en utilisant une boucle foreach.
<?php
$produits = array("pomme" => 1.5, "banane" => 2.0);
foreach ($produits as $nom => $prix) {
echo $nom . " : " . $prix . " euros<br>";
}
?>
8.Créer un tableau à deux dimensions contenant les notes de 3 élèves pour 3 matières et afficher son contenu
<?php
$notes = [
[12, 15, 14],
[10, 11, 12],
[18, 16, 17]
];
for ($i = 0; $i < count($notes); $i++) {
for ($j = 0; $j < count($notes[$i]); $j++) {
echo $notes[$i][$j] . " ";
}
echo "<br>";
}
?>
