PHP Loops
Loops are used to execute a block of code repeatedly as long as a specified condition is true. They are essential for tasks like iterating through arrays, repeating operations, or automating repetitive tasks.
लूप्स का उपयोग एक ही कोड को बार-बार चलाने के लिए किया जाता है जब तक कि कोई निश्चित शर्त पूरी न हो जाए। ये सरणियों पर लूप चलाने, दोहराए जाने वाले कार्यों को स्वचालित करने के लिए उपयोगी होते हैं।
PHP for Loop
Used when the number of iterations is known.
जब iterations की संख्या पहले से पता हो, तब for loop का उपयोग किया जाता है।
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
?>
PHP while Loop
Used when the number of iterations is not known beforehand.
जब iterations की संख्या पहले से पता न हो, तब while loop का उपयोग किया जाता है।
<?php
$x = 0;
while ($x < 3) {
echo "Value: $x\n";
$x++;
}
?>
PHP do...while Loop
Executes the block once, then checks the condition.
ब्लॉक कम से कम एक बार चलता है, फिर शर्त की जाँच की जाती है।
<?php
$y = 0;
do {
echo "Count: $y\n";
$y++;
} while ($y < 2);
?>
PHP foreach Loop
Used for looping through arrays.
सरणियों के लिए foreach लूप का उपयोग किया जाता है।
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "$color\n";
}
?>