PHP Loop: For, ForEach, While, Do While [Exempel]

โšก Smart sammanfattning

PHP Loops repeat a block of code until a condition is met, which removes repetitive typing and drives array processing. This walkthrough covers the four PHP loop types, for, foreach, while, and do-while, with syntax, flowcharts, and working output for each.

  • ๐Ÿ” What Loops Do: A loop runs the same block repeatedly until its condition is satisfied, saving you from writing duplicate statements.
  • ๐Ÿ”ข Fรถr loop: for combines the counter, condition, and increment on one line, making it ideal when the iteration count is known.
  • ๐Ÿ“ฆ Foreach Loop: foreach iterates through every element of an indexed or associative array without a manual counter.
  • ๐Ÿ”„ Medan loop: while checks its condition before each pass, so the body may run zero times if the condition starts false.
  • 1๏ธโƒฃ Do-While Loop: do-while checks the condition after the body, which guarantees the code block executes at least once.
  • ๐Ÿงญ Choosing a Loop: Pick for and foreach for counting and arrays, while for condition-driven repeats, and do-while when one guaranteed pass is required.
  • ๐Ÿค– AI Assist: AI tools can refactor loops, convert a for loop into array functions, and locate the cause of an infinite loop.

PHP Loops

A loop is an iterative control structure that involves executing the same block of code a number of times until a certain condition is met. PHP supports four loop types, compared in the table below.

loop Bรคst fรถr Condition checked Runs at least once
fรถr A known number of iterations Before each iteration Nej
fรถr varje Iterating over array elements Per array element Nej
medan Repeating while a condition holds Before each iteration Nej
gรถra medan Running once, then re-checking After each iteration Ja

PHP fรถr loop

The for loop executes a block of code a specified number of times. It is the right choice when you know in advance how many iterations are needed.

syntax. Den har fรถljande grundlรคggande syntax.

<?php
for (initialize; condition; increment){

// code to be executed

}
?>

Hร„R,

  • "fรถrโ€ฆ{โ€ฆ}" รคr slingblocket
  • "initialiseraโ€ is usually an integer; it is used to set the counterโ€™s initial value.
  • "skick" is the condition that is evaluated for each PHP execution. If it evaluates to true, then execution of the for loop continues. If it evaluates to false, the execution of the for loop is terminated.
  • "รถkning" is used to increment the initial value of the counter integer.

Hur det fungerar. The flowchart shown below illustrates how the for loop in PHP fungerar.

PHP fรถr loop

How to code. The code below uses the for loop to print the values of multiplying 10 by 0 through to 9.

<?php

for ($i = 0; $i < 10; $i++){

$product = 10 * $i;

echo "The product of 10 * $i is $product <br/>";
}

?>

Produktion:

The product of 10 * 0 is 0
The product of 10 * 1 is 10
The product of 10 * 2 is 20
The product of 10 * 3 is 30
The product of 10 * 4 is 40
The product of 10 * 5 is 50
The product of 10 * 6 is 60
The product of 10 * 7 is 70
The product of 10 * 8 is 80
The product of 10 * 9 is 90

PHP Foreach Loop

The PHP foreach loop is used to iterate through array values. It has the following basic syntax.

<?php
foreach($array_variable as $array_values){

block of code to be executed

}
?>

Hร„R,

  • "fรถr varje(โ€ฆ){โ€ฆ}" is the foreach loop block code
  • โ€œ$array_variableโ€ รคr arrayvariabeln som ska loopas igenom
  • โ€œ$array_valuesโ€ is the temporary variable that holds the current array item value.
  • "kodblock..." รคr den kodbit som fungerar pรฅ matrisvรคrdena

Hur det fungerar. The flowchart shown below illustrates how the foreach loop works.

PHP fรถr varje slinga

Praktiska exempel. The code below uses the foreach loop to read and print the elements of an array.

<?php

$animals_list = array("Lion","Wolf","Dog","Leopard","Tiger");

foreach($animals_list as $array_values){

echo $array_values . "<br>";

}

?>

Produktion:

Lion
Wolf
Dog
Leopard
Tiger

Let us look at another example that loops through an associerande matris. An associative array uses alphanumeric words for access keys.

<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

foreach($persons as $key => $value){

echo "$key is $value"."<br>";

}

?>

Namnen har anvรคnts som arraynycklar och genus som vรคrden.

Produktion:

Mary is Female
John is Male
Mirriam is Female

PHP While Loop

The while loop is used to execute a block of code repeatedly until the set condition is satisfied.

Nรคr du ska anvรคnda while-slingor

  • Medan loopar anvรคnds fรถr att exekvera ett kodblock tills ett visst villkor blir sant.
  • Du kan anvรคnda en while-loop fรถr att lรคsa poster som returneras frรฅn en databas.

Typer av while-slingor

  • Gรถra medan โ€“ exekverar kodblocket minst en gรฅng innan villkoret utvรคrderas
  • Medanโ€ฆ โ€“ kontrollerar tillstรฅndet fรถrst. Om det utvรคrderas till sant, exekveras kodblocket sรฅ lรคnge villkoret รคr sant. Om det utvรคrderas till falskt, avslutas exekveringen av while-slingan.

While loop. Den har fรถljande syntax.

<?php
while (condition){

block of code to be executed;

}
?>

Hร„R,

  • "medan(โ€ฆ){โ€ฆ}" รคr while-slingans blockkod
  • "skick" รคr villkoret som ska utvรคrderas av while-slingan
  • "kodblock..." รคr koden som ska kรถras om villkoret uppfylls

Hur det fungerar. The flow chart shown below illustrates how the while loop works.

Medan Loop

Praktiskt exempel. The code below uses the while loop to print numbers 1 to 5.

<?php

$i = 0;

while ($i < 5){

echo $i + 1 . "<br>";

$i++;

}

?>

Produktion:

1
2
3
4
5

PHP Do While Loop

The difference between the while loop and the do-while loop is that the do-while loop is executed at least once before the condition is evaluated.

Let us now look at the basic syntax of a do-while loop.

<?php
do{

block of code to be executed

} while(condition);
?>

Hร„R,

  • "gรถra medan(โ€ฆ)" is the do-while loop block code
  • "skick" รคr villkoret som ska utvรคrderas av while-slingan
  • "kodblock..." is the code that is executed at least once by the do-while loop

Hur det fungerar. The flow chart shown below illustrates how the do-while loop works.

PHP gรถr medan

Praktiskt exempel. We are now going to modify the while loop example and implement it using the do-while loop, and set the counter initial value to 9.

The code below implements the above modified example.

<?php

$i = 9;

do{

echo "$i is"." <br>";

}
while($i < 9);

?>

Ovanstรฅende kodutgรฅngar:

9

Anmรคrkningar: the above example outputs 9 only. This is because the do-while loop is executed at least once even if the set condition evaluates to false.

Vanliga frรฅgor

Yes. Use array_reverse() with a foreach loop to walk the elements in reverse, or use a for loop that starts at count($array) โ€“ 1 and decrements the index down to zero.

The break statement accepts a number, so break 2; exits both the inner and the outer loop at once. This is cleaner than using a flag variable to stop the outer loop.

An infinite loop never ends because its condition never becomes false, often due to a missing increment. Ensure the loop variable changes each pass, or add a break when a limit is reached.

Yes. AI can spot repeated work inside a loop, suggest moving it outside, and replace manual loops with array functions like array_map or array_filter where they make the code clearer.

Yes. AI can rewrite an index-based for loop as a foreach when you are walking an array, or as array_map or array_sum when the loop just transforms or totals values. Test the output afterward.

Sammanfatta detta inlรคgg med: