PHP - Using do...while loops

Introduction

If the expression you're testing relies on setting a variable inside the loop, you need to run that loop at least once before testing the expression.

Demo

<?php

          $width = 1;/*  w ww .j  a va2  s . c  o m*/
          $length = 1;

          do {
            $width++;
            $length++;
            $area = $width * $length;
          } while ( $area  <  1000 );

          echo "The smallest square over 1000 sq ft in area is $width ft x $length ft.";
?>

Result

This script computes the width and height of the smallest square over 1000 square feet in area.

It initializes two variables, $width and $height.

Then creates a do...while loop to increment these variables and compute the area of the resulting square, which it stores in $area.

Because the loop is always run at least once, you can be sure that $area will have a value by the time it's checked at the end of the loop.

If the area is still less than 1000, the expression evaluates to true and the loop repeats.

Related Topic