PHP do while loop Statement Example

529 views 11 months ago PHP

You have already known how loops in any programming language works. Every programming language has few loops like for loops and while loops. In PHP, there are four loops for loop, while loop, do...while loop and foreach loop to loop through data.

while and do...while loops are conditional loops. It only loops if the given condition is true. Sometimes you may want to execute some blocks of code at least one time before checking condition. In this situation, you may use do...while loop.

Syntax:

do {
    statement;
} while (condition);

statement will execute if the condition is true.
condition to be checked before statement execute.

Usage

do...while loop always execute statement before checking condition.

Example:

<?php
$x = 1;
do {
    print($x);
    $x++;
} while ($x <= 10);
// 1 2 3 4 5 6 7 8 9 10

This is simple example. In the real world coding, you can use do while condition as below example.

<?php
do {
    $api_key = str_random(20);
    $check = mysqlGetData("SELECT api_key from USERS where api_key=".$api_key);
} while ($check != null);
// there is no record
// you can now work with check

In the above function we first run and generate Api Key. And then find any record with mysqlGetData() function that record exists. In the condition we generate Api key until we don't get record.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Search
Advertise

Ezoicreport this ad