#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0

    Post About a small code


    Hello,I am novice in PHP.I just got a doubt going on a piece of code.

    1 while($key=key($capitals))
    2 {
    3 printf("%s </br>",$key);
    4 next($capitals);
    5 }

    In line 1, key($capitals) returns a string not a boolean value and it is just an assignment not "==".I am confused how this statement worked.
  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6352
    key() returns null when it hits the end of the array. If you put an assignment inside a control structure's condition, whatever got assigned is used as the check. PHP's atomic operations, themselves, have boolean value. You can say:
    $a = ($b = key($c);

    $a and $b would be identical in this scenario. This behavior is often used as a shortcut to replace:

    while ( null !== ( $a = key($c) ) )

    Since key() returns null when it hits the end of the array, the result of the assignment will be null, which in PHP is == false (thanks to loose typing) and the while loop will halt when the array runs out. Technically what you have is valid, but as you've discovered it's confusing.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0
    Thank You..Helped a lot

IMN logo majestic logo threadwatch logo seochat tools logo