Web Analytics Made Easy -
StatCounter PHP - Frequently Asked Questions - CodingForum


No announcement yet.

PHP - Frequently Asked Questions

  • Filter
  • Time
  • Show
Clear All
new posts

  • PHP - Frequently Asked Questions

    Ok, Im starting this FAQ thread for the PHP forum. This will work pretty much the same as all the other FAQ threads.

    We seriously need some new tutorials added, if you have the time, please go here: <https://www.codingforum.net/node/37067> and consider submitting a tutorial!

    Please do not reply to this thread asking for help, if you are still having problems, start a new topic in the relevant forum describing your problem

    General Rules
    • Please feel welcome to contribute to this thread, but please dont post unless you are adding a good answer to a frequently asked question.
    • If you do contribute, each post should contain one question and answer, no more, no less.
    • Please put keywords or function names that are not within PHP code blocks in blue text.
    • PHP code should be placed in PHP code blocks.
    • When you write a reply, please include links to php.net with the relevant resources.

    For further information on how to add a reply, or if you would rather have your answer proof-read before you post it here (reccomended), then please visit <https://www.codingforum.net/node/37067>

    FAQ Index
    1. My code isn't working, and I get no errors!
    2. Why PHP/JavaScript?
    3. GPC Stripping Tutorial - Magic Quotes
    4. Outputting Data/Common Mistypes
    5. What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?
    6. How do I write to a file using PHP?
    7. How do I read a file using PHP?
    8. Permission denied ... why ? File permissions
    9. How do I resolve the 'headers already sent' error?
    10. How do I make a random password function ?
    11. What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?
    12. Sending HTML email with PHP
    13. TIP: Coding styles and $end errors
    14. TIP: Quotes / Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in..
    15. The IE if (isset($_POST['submit'])) bug explained.

    As FAQ entries get added I will add them to the index here.


    php.net - The official PHP site, where you can download the latest versions of PHP or lookup functions and syntax.
    mysql.com - MySQL is the database technology that is most often used with PHP, to make dynamic data driven websites and scripts
    Last edited by Fou-Lu; Oct 6, 2011, 07:24 PM. Reason: Updated FAQ Index to include newer posts
    PHP Weekly - A PHP Developers Resource
    PHP 5.1.4 and Ruby on Rails web hosting
    Moderator of PHP and Work offers and Requests
    Install Apache/PHP/MySQL
    (by marek_mar) | TinyPlugin Architecture

  • #2
    Q. How do I write to a file using PHP?

    A. This question is often asked in many ways, it could be how to add something to the end of a file, empty a file, or create a file. All of these operations come under writing to a file.

    Firstly, there is a basic pattern to writing to a file, it goes something like this:
    1. Open the file using fopen
    2. Lock the file using flock
    3. Write to the file using fputs or fwrite
    4. Unlock the file using flock
    5. Close the file using fclose

    This is the order that the operations (usually) need to be carried out in. The following example shows you how to create a file, then write a string to the file.

    Handle - The name often given to the variable defined when using the fopen function.
    Mode - A letter that represents how the file should be opened when using fopen.

    PHP Code:

    fopen('filename.txt''w'); // set the handle to the variable $fp
    // and open the file in "w" mode.

    $string 'Test String'// set the $string variable

    flock($fpLOCK_EX); // lock the file "exclusivley" for writing

    fputs($fp$string); // write the data to the file

    flock($fpLOCK_UN); // unlock the file

    fclose($fp); // always call fclose to close the file.
    // forgetting to close or lock files is the main cause of
    // files getting corrupted.

    1. Now, to go over the example, the first line, where the fopen function is used, opens the file in writeable mode... If the file does not exist it will attempt to create it. The important thing to remember about using the "w" mode in fopen is that any data in the file will be truncated (emptied). There are other file handling modes, which can be looked up on the php website: <http://www.php.net/fopen>. Some of these other modes will also be covered later in this post.

    On the next line, we just simply set the variable $string to the value 'Test String'. This is the data that will get written into the file later on.

    2. Next we lock the file using flock. Using an exclusive lock, which is set by putting LOCK_EX, the file is locked from other scripts writing to the file or reading from it while we put the new information into the file. If the file isn't locked and two scripts try to write to it at the same time, it can get corrupted.

    3. The next part is the part that actually writes the information to the file. Using the fputs function it use the file path and data supplied ($fp and $string in this case), and writes $string to $fp.

    4. From here, the file needs to be unlocked using flock again, otherwise no other scripts would be able to write or read it. To unlock the file, we use LOCK_UN.

    5. Finally, we have finished with the file so we can close it. Using the fclose function we pass it the file handle ($fp) and it closes it. You should always do this as this is another thing that can lead to files getting corrupted.

    If you try this and are still having problems, there are some possible reasons that it is failing, the most likley is that the file or directory you are trying to write to doesn't have the right permissions set. If you are on Linix machines (mosts PHP hosts will be running Linux), then you can CHMOD the file or directory to a value that will allow the scripts to be executed. For testing, I usually set it to 777. You can CHMOD from some FTP programs and online control panels. If you are not sure how to CHMOD on your hosting acount, you should contact your webspace provider.

    This is the basics of writing to a file. Often, however, when you write to a file, you want to be able to add something on to the end of the file, and not delete everything that is in there first. This is very easy to alter, simply change the code:

    PHP Code:

    // to

    This changes the file from opening to write mode (w) to ammend mode (a). When you write to the file now, anything you write to the file gets added onto the end after any existing data.

    Finally, to bring this to a close, just a couple more points...
    1. This only handles with writing to files, you can also read from filed but that is not discussed here
    2. There are many more modes for file handling, look at <http://www.php.net/fopen>
    3. There are also other types of file lock, and you can find these at <http://www.php.net/flock>

    How to write to the beginning of a file?
    A common question is ,'how do you write to the beginning of a file' , the answer is not a new magic mode but a different approach , it should be noted that you can write to the beginning of a file by opening 'r+' and using fseek() to rewind to the start of a file then fputs() etc , however this will overwrite byte for byte the files existing contents.

    To add a line to the beginning of a text file the most straightforward method is to read the file into memory , manipulate and then rewrite the file.
    Newer PHP versions have handy functions such as file_get_contents() to get the files data into a variable , you can also use the above noted functions to read a file into memory or the old sausage <?$str = implode( '', file( $filename ) ) ;?>

    e.g. (no filelocking for clarity)
    PHP Code:
    read the file contents into a variable
    'cars.txt' ;
    $str implode'' file$filename ) ) ;
    append your data
    "porche 911sc\n" $str ;
    open (overwrite) your existing file
    fopen$filename ,'w' ) ;
    fputs$fp $str ) ;
    fclose$fp ) ;
    Note that the above method becomes resource intensive with larger files.

    Last edited by firepages; Apr 6, 2004, 10:43 AM.
    PHP Weekly - A PHP Developers Resource
    PHP 5.1.4 and Ruby on Rails web hosting
    Moderator of PHP and Work offers and Requests
    Install Apache/PHP/MySQL
    (by marek_mar) | TinyPlugin Architecture


    • #3
      permission denied ... why ? file permissions

      <help>I would really appreciate those of you who understand all of this to please check the below is in order since it is a sticky , I am not a unix user , not a trained administrator so any pointers errata are welcomed !!!</help>

      OK so many questions regarding this subject so...here we go.

      Files on any *NIX system have a, at first glance ,complex ownership/permission system , its actually not that complex but can be intimidating at first.
      Now you may think you don't need to understand them (and for most web-related work you probably don't ), however knowledge is power & once you do understand them , you will never again worry about the dreaded `permission denied` , dont skip though , read from the beginning , it makes more sense if you do.

      The 3 common (there are more) *NIX permissions 'r' , 'w' , 'x' ( often 'e' or 'o' ) are applicable to 3 entities , the files 'owner' the files 'group' and 'others' (AKA 'everyone else' 'the world' )

      All files have an owner , who that owner is depends on who created them , when you upload a file via FTP the file is owned by the user that you logged in as.
      So if your FTP login is 'joe' then the file is most likely owned by user 'joe'.

      When however you create a file via script (fopen() etc) the file is still owned by whoever created it , however that user is no longer 'joe' , its the user that your webserver runs as , which is normally NOT your *UNIX username (except in chrooted or suexec environments) , it is normally 'apache' or 'nobody' .

      Groups are a bit of a sticky subject because how groups are assigned varies from system to system , often at the whim of the server administrator or hosting control panel interface , plesk for example assigns all file uploaded via FTP to the 'psacln' group , redhat however by default creates a new group for each user and assigns group ownership to that group (e.g. user 'joe' gets his own group 'joe').

      Others AKA everyone else , the world
      As far as *NIX is concerned , if someone is not the owner of the file or does not belong to the same group as a file , then you are classed as 'others' , contrary to popular belief external applications can not modify files which allow write access to 'others' , only other users of the same system or local network can actually do that (on shared hosting this is a real issue)

      All *NIX files have permissions assigned , there are 3 permissions a file can be given , 'r' for read , 'w' for write & 'x' for executable , a file can have 0 or more permissions . e.g. a file can have both 'r' and 'w' permissions , so they are both readable and writable , 'rwx' means you can do pretty much anything with the file.

      Now the permissions above r,w & x are applied individually to the files owner , the files group and others ! so

      owner group others user group
      myfile rwx r r joe joe

      With the above, the owner of the file (joe) can read write & execute (if applicable , e.g. the file is a script) the file , any members of the 'joe' group (usually just the user joe) can read and write to the file , 'others' can only read the file. when your webserver requests myfile , it does so as 'apache' or nobody' and as such is given read access.

      However , when your script which is probably running as 'apache' comes along and tries to write to the file , it finds it can not .. why? , well 'apache' is not the owner of the file , nor does it belong to the group 'joe' , therefore as far as this file is concerned it belongs to the 'world' group which is only allowed to read, not write to the file.

      to allow apache to write to the file you would need to change the file permissions to ...

      owner group others user group
      myfile rwx rw rw joe joe

      e.g. give 'others' write 'w' access , so an outsider , such as apache , could write to the file.

      Now lets say you created a file via a PHP script , the file created by PHP (actually by apache with mod_php) will be owned by 'apache' , if you then chmod the file (again via script) to say 0700 (rwx------) then you would not have permission to delete that file via FTP , since you would then be considered as 'others' !
      Luckily if you created a file by script you can chmod it to something more accessible via script <?php chmod( 'myfile' , 0766 );?> , this will then allow you to read and write to the file via FTP.

      so with the following
      owner group others user group
      myfile rwx r r joe joe

      You can not chmod the script via PHP/apache since it only has read access , however if via FTP you (as 'joe') chmod to 0766 or 0777 , then your PHP script can read and write to the file.

      Its often assumed that if a directory is not writable then nor are is contents , that however is <B>not</B> the case , a writable file in a read-only directory can still be altered by anyone with the right credentials , however you will not be able to write to that directory unless the directory is writable to the user or application that attempts the write.
      Also to be able to list the directories contents , the directory must be executable to the application attempting to do so , 'read' is not enough (in fact you don't even need the directory to be readable , 'x' is enough.

      Need to be executable , HTML & text files etc can simply be read-only , but if a file is a script , then make it executable !

      .................................................................................................... .............................

      file permissions can be represented as octal modes , but that's easier than it sounds , if ...
      r (read) = 4
      w (write) = 2
      x (execute) = 1

      if the owner of a file has read & write permissions that's 4+2 = 6
      if the group just has read permission that's 4
      if others also only have read permissions , again that's 4

      so myfile below has the mode 0644
      owner group others user group
      myfile rw r r joe joe

      .................................................................................................... .............................

      As noted above chmod() can change the permissions of a given file , for a user or an application to change these permissions however the user or application needs to have write access to the file in the first place !!

      for PHP its important when chmod()'ding to use octal values
      chmod( 'myfile' , '0644' ) ; will cause issues , since we are passing the mode as a string
      chmod( 'myfile' , 644 ) ; here 644 , is , as far as PHP is concerned, decimal ! again be prepared for problems
      chmod( 'myfile' , 0644 ) ; is correct !

      .................................................................................................... .............................

      chown & ghgrp
      PHP has the chown & chgrp commands, however only a superuser can use them , so unless your webserver runs as 'root' or similar , you can't use them.

      .................................................................................................... .............................

      CGI disclaimer
      If your server runs PHP as a CGI then much of the above may change , its is not common for CGI scripts to be run as a different user than the webserver via Apaches mod_suexec or phpsuexec etc

      .................................................................................................... .............................

      chrooted environments
      If you webserver runs in a chrooted environment then its possible (probable) that the webserver (above stated as 'apache' or 'nobody') may well run as another user , often as the user account e.g the same as your FTP login , if this is the case then you will have less issues with file ownership & generally be in a much safer playground.

      Not really important here , but you may wonder why when you create a file via FTP or script that it is given e.g. 0755 for FTP or 0644 for scripts , this is decided by the umask , the responsibility of the server administrator

      .................................................................................................... .............................
      .................................................................................................... .............................

      So , if you read the above , and if it made any sense at all , you will understand why you can't ,immediately alter your files uploaded by FTP via a PHP script, if you don't then read again , if I am making no sense then please post and say so & I will try and clarify , if anyone wants to add to this document , post & I will add/amend
      resistance is...

      MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)


      • #4
        How can i do a random password function ?

        Q: How can i do a random password function ?

        There it is,
        First of all, you need a character bank as well abcdefghijklm...etc..,
        It looks that you want a password generated by the server, so you need to specify all your chars and yes, Upper cases too..
        1. STEP 1 , Create a file called functions.php and add this content..
          PHP Code:
           // File functions.php
          function randompassword() {  // Declaring the function
          //Config Start
          $salt "abchefghjkmnpqrstuvwxyz0123456789"// Your characters bank
          $n "8";                                   // Number of character to return
          //end config
          $v strlen($salt);
          $i 1;
                while (
          $i <= $n) {
          $num rand() % $v;
          $tmp substr($salt$num1);
          $pass $pass $tmp;
          Please note, that functions with those structures doesnt called by itself, so you must call it to get results..Let's do it..
        2. STEP 2, in any files who needs a random password, add this to require the file who contain functions at page load, and declare the variable to get the password..

          PHP Code:
           // File index.php
          <? require("functions.php"); ?>
               Some meta-head infos
               Some javascript scripts..etc..
               Some contents
          randompassword(); // $password gonna call the function randompassword and return it into  the variable..
          echo "There's my password:  ".$password."     ";
              Some contents   


        Functions used in this scripts are:

        substr Return parts of a $string
        $i++ Increment / Decrement variables
        srand Seed the random number generator < PHP 4.2
        microtime Return current Unix timestamp with microseconds
        rand Generate a random integer
        strlen Return lenght of a string
        Last edited by tomahack; Mar 5, 2005, 08:20 PM.


        • #5
          Very begginner question:

          Why PHP/JavaScript?

          PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.


          • #6
            Q: How to resolve the 'headers already sent' error?
            A: This is one of the most common errors. You often get it when your using session_start() or header().
            Headers are sent automatically when any output is sent to the user. You send output with print/echo (and some other functions) as well as having anything outside php tags. This includes blank lines spaces, tabs and all other characters. You must send the header BEFORE the output. You must watch out not to have any blank lines before the <?php tag and after the ?> tag
            PHP Code:
            <?php // There should be no spaces before tag.
            // A new line which shouldn't be here. This is important especially the file is included to another file.
            Coding in such a way might be difficult, so you might ask if there is a way to wait with sending the output until the end of script execution. This is where output buffering (ob for short) comes in to play. If you start ob it will save all output and headers into memory instead of sending it. You can send all output at once with the headers.
            PHP Code:
            (); // Send the output. 
            <title>OB test</title> 
            ('Content-type: text/plain'); // An example header.
            ob_end_flush(); // Send the output. 
            You can try commenting out the ob_start();

            Functions used:
            -mentioned but not OB functions
            Good to read:
            output buffering

            If you spot an error (or have a suggestion) PM me. I'll fix it as fast as I can.
            I'm not sure if this was any help, but I hope it didn't make you stupider.

            Experience is something you get just after you really need it.
            PHP Installation Guide Feedback welcome.


            • #7
              Originally posted by thewickedjester
              Very begginner question:

              Why PHP/JavaScript?

              PHP is server side, while JavaScript is client side, meaning that JavaScript can make popups and other things happen on someones PC, while PHP is server-side, so it does stuff with the server.
              PHP and JavaScript can be used together also (you can put <?php echo whatnot ?> in <SCRIPT> tags, just as you can put <script>some js here</script> in <?php ?> tags (with the echo before each js command, of course)
              PHP is used to load a page and can be put into certain js variables etc (for instance taking items from a database and putting them into js variables, you would use php in script tags OR if you want to make a certain part of your page scale to the length of your database but have JS inside of it, you would use php to make the length of whatever it is (say <TD>s) and put JavaScript inside each TD.
              Just because JS and PHP are client-side and server-side respectively does not mean they cannot be used together. JS makes pages dynamic (on the client side) while PHP makes pages dynamic (on the server side, when the page actually loads (the user does not see how the php affects the page)).


              • #8
                Q: What is the difference between addslashes() and mysql_real_escape_string() when running MySQL queries?

                A: The difference between addslashes() and mysql_real_escape_string() is that mysql_real_escape_string() escapes all characters harmful to a mysql query (such as line feeds, carriage returns, quotes, and a number of other assorted special characters), while addslashes() only escapes quotes (both single and double), backslashes, and the NULL byte.

                Related to this topic is magic quotes. If magic_quotes_gpc is enabled in the PHP config, it automatically runs the equivalent of addslashes() on $_POST, $_GET, and $_COOKIE data (and by proxy, $_REQUEST data). If magic_quotes_runtime is enabled, it runs it on almost all external data (file reads, database results, and so on). Thus, we would want to remove this from our data before entering, as when used with mysql_real_escape_string() it would double-escape values, and would cause errors.

                PHP Code:
                $username $_POST['username']; // Value is ' OR ''=', which would be executed as part of the query without escaping.

                if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) { // Check if either magic_quotes_gpc or magic_quotes_runtime are enabled.
                $username stripslashes($username); // Strip the slashes added by magic quotes.

                $username mysql_real_escape_string($username); // String is now safe to use in a query. 
                One more warning is to not use mysql_real_escape_string() on integers. You can, but all it will do is convert them to strings, and there are ways to do so with far less overhead. You may want to write a function which acts as a wrapper for mysql_real_escape_string() and checks if it is an integer first.


                Magic Quotes
                "$question = ( to() ) ? be() : ~be();"


                • #9
                  Q: What is the difference between using $HTTP_POST_VARS and $_POST for accessing POST variables?

                  A: The difference between $HTTP_POST_VARS and $_POST is that one is depricated, and one is not. $HTTP_POST_VARS (and others such as GET, SERVER, ENV, COOKIE, etc.) were all renamed in PHP 4.1.0 to variables such as $_POST, $_GET, $_SERVER, $_ENV, $_COOKIE, and so on. In later versions of PHP (possibly PHP6) they will be eventually removed.

                  It is noteworthy to say that the $HTTP_POST_VARS array and the $_POST superglobal array are not references...that is to say, they are separate variables. Changing the value of $_POST['foo'] will not modify the value of $HTTP_POST_VARS['foo'].


                  Predefined Variables
                  "$question = ( to() ) ? be() : ~be();"


                  • #10
                    How do I read a file using PHP?

                    How do I read a file using PHP?
                    The following are basic steps followed in reading a file using PHP
                    Open a file using fopen
                    lock the file using flock
                    read the contents of the file using fread
                    unlock the file using flock
                    close the file using fclose
                    PHP Code:
                    "../example/file.txt"//name of file
                    $handle fopen($filename"r"); //open the file using fopen
                    flock($handle,LOCK_SH);//lock the file using shared lock for reading
                    $contents fread($handlefilesize($filename));//read the file using fread
                    echo $contents//display the contents of file
                    fclose($handle);//close the file using fclose
                    1. The first line of the code specifies name of the file.
                    2. Then open the file using fopen in "r" read mode. If the file doesn't exists, it will show you an error.
                    3.Lock the file using flock.using an shared lock,which is set by putting LOCK_SH.When a statement reads data without making any modifications, its transaction obtains a shared lock on the data.
                    4.Read the data from the file using fread. Read the file until end of the file will be reached.
                    5.unlock the file using flockby putting LOCK_UN
                    6.close the file using fclose


                    • #11
                      Sending HTML email with PHP

                      I read a really good article about the PHP emailing program PHPmailer and decided to check it out.

                      Heres how I use it to send HTML emails on my sites:

                      class MyMailer extends PHPMailer {
                          public $From = "[email protected]";
                          public $FromName = "Google.com";
                          public $Host = "mail.google";
                          public $Hostname = "google";
                          public $Mailer = "smtp";
                          public $Sender = "[email protected]";
                          public $SMTPAuth = true;
                          public $Username = "[email protected]";
                          public $Password = "youwish";
                      $emailresults = '<html><head><title></title></head><body>
                      <div style="position:relative; margin:40px 0; padding:1px;">'.$myformss.$debugger.$mess.'</div></body></html>';
                      if(!isset($_SESSION['mailsent'])) $_SESSION['mailsent']=0;
                      else $_SESSION['mailsent']++;
                      if ($_SESSION["mailsent"] < 10) {
                          $mail = new MyMailer();
                          $mail->AddAddress("[email protected]");
                          $mail->AddBCC("[email protected]");
                          $mail->Subject = $mysubject;
                          $mail->Body = $emailresults;
                          $mail->AltBody = "You are viewing this message because your email client is not configured for html emails.$mess";
                              echo "Message was not sent<br>";
                              echo "Mailer Error: " . $mail->ErrorInfo;
                          } else $mail->ClearAllRecipients();
                      } else die('MAILSENT OVER LIMIT!');
                      Apache htaccess Google Group


                      • #12
                        Outputting Data
                        • echo "Hello<br/>$name"; // Works!
                        • echo "Hello\n$name"; // Works!
                        • echo 'Hello\n$name'; // outputs "Hello\n$name"

                        Why is this?
                        functions used with single quotes is used as direct/literal input, and text within single quotes does not get parsed.

                        Common Mistypes
                        PHP Code:
                        if ($variable $condition)  // will always return as true
                        if ($variable == $condition)  // correct usage 
                        PHP Code:
                        if ($variable !== $condition)  // enforces type comparison: http://php.net/language.operators.comparison
                        if ($variable != $condition)  // correct usage 
                        PHP Code:
                        fputs($fp'This is text\n'); // does not make a new line
                        fputs($fp"This is text\n"); // this does make a new line 
                        Note from Inigoesdr: While you can use any of these and/or examples, you probably want the one marked "correct". See this manual page for more info; specifically precedence.
                        PHP Code:
                        if ($variable == $condition AND $other != $condition)  // incorrect usage
                        if ($variable == $condition && $other != $condition)  // correct usage

                        if ($variable == $condition OR $other != $condition)  // incorrect usage
                        if ($variable == $condition || $other != $condition)  // correct usage 
                        PHP Code:
                        // Incorrect
                        if ($variable == $condition
                        // Correct
                        if ($variable == $condition) {
                        More info on control structure syntax is available here.

                        There's also the alternative syntax for control structures available to you.
                        Last edited by Inigoesdr; Feb 23, 2008, 09:19 AM. Reason: Consolidating posts


                        • #13
                          My code isn't working, and I get no errors!

                          First and foremost: Turn on error reporting at the very beginning of your script.
                          PHP Code:
                          error_reporting (E_ALL);
                          If you have MySQL queries that aren't working add some error logic to find out why. See the manual for some examples.

                          Also, be sure output buffering is off: ob_end_flush()

                          And if you can't figure it out after that, post a new thread in this forum with as much relevant information as possible, and any code that we might need so we can help you as quickly as possible.
                          Last edited by Inigoesdr; Nov 16, 2008, 01:20 PM.


                          • #14
                            Alternating Rows

                            How do I determine alternating rows?
                            Common question when using loops and css divs or tables. There are two ways to determine whether you're current iteration is odd or even. One way is through modulus (remainder) division, and the other way is through bitwise comparison. Bitwise comparison is faster than modulus since only the least significant bit needs to be checked. This equates to approximately 2 - 3 times faster than modulus division.

                            PHP Code:
                            $aItems = array('Cat''Dog''Mouse''Rabbit');
                            $cItems sizeof($aItems);
                            for (
                            $i 0$i $cItems; ++$i)

                            In the above example, $i represents even if one of the following is true:
                            PHP Code:
                            $bIsEven = ($i == 0); // Most common way
                            $bIsEven = !($i 1); // Faster though less used. 
                            Conversely, $i is odd if the above are false:
                            PHP Code:
                            $bIsOdd = ($i != 0);
                            $bIsOdd = ($i 1); 
                            Using this with the previous loop, the alternating rows would correspond with the classes 'evenRow' and 'oddRow':
                            PHP Code:
                            $aItems = array('Cat''Dog''Mouse''Rabbit');
                            $cItems sizeof($aItems);
                            for (
                            $i 0$i $cItems; ++$i)
                            $sClass 'evenRow';
                                if (
                            $i 1)
                            $sClass 'oddRow';

                            printf("<div class=\"%s\">%s</div>\n"$sClass$aItems[$i]);

                            Results in:
                            <div class="evenRow">Cat</div>
                            <div class="oddRow">Dog</div>
                            <div class="evenRow">Mouse</div>
                            <div class="oddRow">Rabbit</div>
                            PHP Code:
                            header('HTTP/1.1 420 Enhance Your Calm'); 
                            Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


                            • #15
                              go here
                              http://www.phpvideotutorials.com/free and check out the free lessons (the first teaches you how to install WAMP)
                              My site: JayGilford.com
                              PHP Pagination Class | Getting all page links | Handling PHP Errors properly
                              If you like a users help, show your appreciation with the rep and thanks buttons :)