Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between an If statement and While loop

Tags:

php

I read this Manual by PHP.com about While loops.

I don't understand the purpose of While loops in PHP.

It looks exactly like an if statement to me.

What is the difference between an if statement and a while loop?

How do while loops work, what do they do, and when should I use them?

For example, can't this:

$i = 1;
while ($i <= 10) {
    echo $i++;
}

be done like this?:

$i = 1;
if ($i <= 10) {
    echo $i++;
}
like image 405
Ben Beri Avatar asked Dec 01 '22 20:12

Ben Beri


2 Answers

An if statement checks if an expression is true or false, and then runs the code inside the statement only if it is true. The code inside the loop is only run once...

if (x > y)
{
   // this will only happen once
}

A while statement is a loop. Basically, it continues to execute the code in the while statement for however long the expression is true.

while (x > y)
{
  // this will keep happening until the condition is false.
}

When to use a while loop:

While loops are best used when you don't know exactly how many times you may have to loop through a condition - if you know exactly how many times you want to test a condition (e.g. 10), then you'd use a for loop instead.

like image 173
dsgriffin Avatar answered Dec 31 '22 22:12

dsgriffin


A while loop will run as many times as it needs to while a condition is true, i.e., until that condition is false.

An if statement will execute once if a condition is true.

A great way to understand concepts like this when you're just learning a language is to try them out:

<?php
$i = 1;
while ($i <= 10) {
    echo $i++;
}

echo "\n";

$i = 1;
if ($i <= 10) {
    echo $i++;
}

This results in:

12345678910
1
like image 24
Tom Smilack Avatar answered Dec 31 '22 22:12

Tom Smilack