fbpx

Multan Institute of Information Technology

PHP Loops For Beginners

Loops

In today’s PHP class, we talked about loops. Loops play a very important role in programming language because they save time and also help us in writing code because adding loops makes our code shorter. If we have to repeat a line, program or a paragraph, then instead of writing it again and again, we use loops. This saves our time and we can write less code.

Types Of Loop in PHP

There are 4 types of loops in PHP

  • While Loop
  • Do-While Loop
  • For Loop
  • Foreach Loop

 

While Loop: We use this loop whenever we get a condition, it keeps running till the condition of any program does not go wrong. When the condition goes wrong it stops.

INPUT:

OUTPUT:

 

Do-While Loop: We use this loop whenever we want to run a program once, even if that condition does not go wrong it definitely runs once.

INPUT:

OUTPUT:

For Loop: You use this loop whenever you know how many times you want to run your code for example like value from 1 to 10..

INPUT:

OUTPUT:

Foreach Loop:  It helps you while working on a page. It allows you to go through a list without any help.

INPUT:

OUTPUT:

conclusion

Loops are also used a lot in backend programming for example making lists, looking up records from a database.. keep running the work until a condition is met.The easiest way to understand loops is that you practice more and more.