Diziyi döngüde gezme
for ve foreach ile bir dizinin tüm elemanlarını döngüde gezeyi öğrenirsin.
for ile indeksli döngü
Bir dizinin tüm elemanlarını gezmek için for döngüsünü indekslerle kullanabilirsin. Sayaç 0'dan başlar, count() değerine kadar gider.
Örneğin:for ($i = 0; $i < count($scores); $i++) { her elemanı sırayla yazdırır.
echo $scores[$i];
}$i indeks olarak kullanılır; $scores[$i] o indeksteki değeri verir.
foreach ile kolay gezinme
Bir diziyi gezmenin en kolay yolu foreach döngüsüdür. İndeks takibi yapmadan her elemanı sırayla alır.
Sözdizimi: foreach ($scores as $score) { ... }. Burada $score her adımda dizinin bir elemanını alır. Örneğin [85, 92, 78] için önce 85, sonra 92, sonra 78 olur. İndeks gerekmiyorsa foreach for'dan daha temizdir.
Uygulama foreach ile notları yazdır
$scores = [85, 92, 78]; dizisini foreach ile gez ve her notu ayrı satırda echo ile yazdır. Her satırın sonuna "\n" ekle. Beklenen çıktı: 85, 92, 78.
Örnek çözümü göster
<?php
$scores = [85, 92, 78];
// foreach ile notları yazdır
foreach ($scores as $score) {
echo $score . "\n";
}
Örnek çözüm:
<?php
$scores = [85, 92, 78];
// foreach ile notları yazdır
foreach ($scores as $score) {
echo $score . "\n";
}
Kendini test et
-
Aşağıdaki kodun çıktısı nedir?
$scores = [10, 20, 30]; for ($i = 0; $i < count($scores); $i++) { echo $scores[$i] . "\n"; }- 0 1 2
- 10 20 30
- 10 20 30
- 30 20 10
Cevabı göster
10 20 30 — Doğru. $i 0, 1, 2 değerlerini alır; elemanlar sırayla yazılır.
-
foreach sözdizimini tamamla
$scores = [85, 92, 78]; ____ $score) { echo $score . "\n"; }Cevabı göster
$scores = [85, 92, 78]; foreach ($scores as $score) { echo $score . "\n"; } -
Döngü ve özelliğini eşleştir
- for
- İndeksle gezme
- foreach
- Elemanla gezme
- count()
- Sınırı verir
-
Bir dizinin yalnızca değerlerine ihtiyaç varsa hangi döngü daha temizdir?
- for
- while
- foreach
- do-while
Cevabı göster
foreach — Doğru. foreach indeks takibi olmadan her değeri verir.