SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2010
    0 Post(s)
    0 Thread(s)

    Don't understand the finer points of the 'while' loop.

    My supervisor at work told me to slightly alter some PHP code from an existing 'view' to put into the new 'view' we were working on. I could not understand what he had done (his code) until I realized (after staring) that he had assigned a variable inside the brackets where the condition for the 'loop' usually sits.

    usually a while loop has a condition that has to be met inside the bracket i.e.
    while ($i <= 10) {
    echo 'hello number'.$i;

    His code iterated over an array, assigning each iteration to a variable and then performing an operation i.e.
    while($somevariable=$someArray[$iCount][$someValue]) {
    echo '$somevariable';

    This absolutely did my head in. I thought he meant '==', not'=', but it was an assignment operator and the code works. Nowhere have I found any mention of PHP working like this. How does this make sense? How is 'assigning an array key's value' a CONDITION? does 'the task of assigning the variable' return true when tested for true or false?


  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Sydney, NSW, Australia
    25 Post(s)
    1 Thread(s)
    He has combined two statements together into one. That single statement is the equivalent of:

    while($somevariable) {

    There are a lot of languages that allow you to combine statements together like that. The problem is that combining statements in this particular situation makes it difficult to spot some sorts of errors - such as where === was what was actually intended as would be more commonly found there.
    Stephen J Chapman, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    1 Post(s)
    0 Thread(s)
    This turns up a lot when you've selected a bunch of rows from a database:

    Code PHP:
    // assuming $result is the result of a SQL query...
    while ($row = mysqli_fetch_array($result)) {
        // do something with the $row variable

    (When there are no more rows in the result set, "mysqli_fetch_array" returns NULL.)

    In your (your boss's) case, when the $iCount variable refers to an array that doesn't exist, it returns NULL, which is false in a boolean context.
    I'm the web overlord for Graphic Business Systems


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts