M. Niyazi Alpay
M. Niyazi Alpay
M. Niyazi Alpay

I've been interested in computer systems since a very young age, and I've been programming since 2005. I have knowledge in PHP, MySQL, Python, MongoDB, and Linux.



  • admin@niyazi.org
PHP For and While Loops

Loops are used to perform repetitive tasks. Initially, it may seem meaningless, but if you have a web page with 100 members, you can finish your work in three lines using a loop instead of writing the names of all of them one by one.

For Loop

The for loop revolves around the given increment value. It repeats the intermediate operations. The syntax is as follows.

for( $variable ; loop condition ; operation to be performed at each turn)

$variable: It allows generating a variable when it starts to rotate.

loop condition: The condition here is actually an IF statement. It continues to rotate if the asked question is true.

operation to be performed at each turn: You don't have to increase one by one during rotation. You can change this operation to count in threes or fives.


for ( $count = 1 ; $count < 10 ; $count++ ){
	echo " I am currently at ".$count. " number";

When you run this command, the following result will be output:

I am currently at 1 number

I am currently at 2 number

I am currently at 3 number

I am currently at 4 number

And so on, it continues 9 times. Since the given condition is $count < 10, the rotation ends when $count == 10.

While Loop

The While loop is a simpler version of the one above. However, it is not only used for numbers since the While loop is only dependent on a single condition, it should be used carefully.


While (Condition)


operation to be performed if the condition is true

Example: Let's do the chicken example.

	echo " I'm hungry, I'm very hungry";

When you run this example, you will see "I'm hungry" printed a million times on the screen. The reason is that $chicken never gets filled, and While asks the same question each turn, if the answer is Yes, it continues to rotate.

When we change the above example as follows, it will only rotate 10 times.

while($chicken < 10){
	echo " I'm hungry, I'm very hungry";
	$chicken = $chicken + 1 ;

The most important part of this example is actually the line $chicken = $chicken + 1, increase the value of $chicken by 1 at each turn.

This post has a version in a different language.
Türkçe: https://niyazi.net/tr/php-for-ve-while-donguleri

You may also want to read these

There are none comment

Leave a comment

Your email address will not be published. Required fields are marked *