Pages

Using Cookies in PHP

Sweeps, Points, Prizes, Play! www.shopyourway.com. Need Help in Web Hosting, Domain, Website Builder, Email and Tools, SSl Certificate? Join with GoDaddy.com

PHP: Cookies


A cookie is a message given to a Web browser by a Web server. The browser stores the message in a small text file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, the cookie is sent back to the server too.
There are a wide variety of things you can do with cookies. They are used to store information about user, visited pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.
Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps ensure the browser sends the correct cookie when a request to a server is made.
Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this case you have to use Sessions.
How to Create a Cookie?
PHP cookies can be set using the setcookie() function. The syntax is as follows:
setcookie(name[, value[, expire[, path[, domain[, security]]]]])
  • [name] The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
  • [value] The  cookie value. It is associated with the cookie name.
  • [expire] The time after which the cookie should expire in seconds
  • [path] Specifies the exact path on the domain that can use the cookies. 
  • [domain] The domain that the cookie is available. If not domain is specified, the default value is the value of the domain in which cookie was created.
  • [security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is sent over a secure connection but it doesn't mean that the cookie is secure. It's just a text file like every other cookie. A value of 0 denotes a standard HTTP transmission.
In the example below, we will create a cookie named "myCookie" and assign the value "PHP Tutorial" to it. We also specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials directory.
<?php
setcookie("myCookie", "PHP Tutorial", time()+3600, "/tutorials");
?>
There's one important item to mention about using cookies. Because of the way cookies work within HTTP, it's important that you send all cookies before any output from your script. This requires that you place calls to this function before any output, including tags as well as any whitespace. If you don't, PHP will give you a warning and your cookies will not be sent.  
How to Retrieve a Cookie Date?
Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the cookie and print out its value on the screen.
<?php
echo "The cookie value is ".$_COOKIE['myCookie'];
?>
This would show up on the page as: "myCookie value is PHP Tutorial".
How to Delete a Cookie?
By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a time for the cookie's expiration but there may be occasions when you need to delete a cookie before the user closes his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past. The example below demonstrates how to do it (setting expiration time 1 minute ago):
<?php
setcookie("myCookie", "", time()-60);
?>
READ MORE - Using Cookies in PHP

DSN and DSN-less connections

Sweeps, Points, Prizes, Play! www.shopyourway.com. Need Help in Web Hosting, Domain, Website Builder, Email and Tools, SSl Certificate? Join with GoDaddy.com

DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN.
For our example below lets assume that our DSN points to an Access database called 'examples.mdb' and that we will be selecting records from the table 'cars'.
<?php

//connect to a DSN "myDSN" 

$conn = odbc_connect('myDSN','','');

if ($conn)
{
  //the SQL statement that will query the database
  $query = "select * from cars";
  //perform the query
  $result=odbc_exec($conn, $query);

  echo "<table border=\"1\"><tr>";

  //print field name
  $colName = odbc_num_fields($result);
  for ($j=1; $j<= $colName; $j++)
  {
    echo "<th>";
    echo odbc_field_name ($result, $j );
    echo "</th>";
  }

  //fetch tha data from the database 
  while(odbc_fetch_row($result))
  {
    echo "<tr>";
    for($i=1;$i<=odbc_num_fields($result);$i++)
    {
      echo "<td>";
      echo odbc_result($result,$i);
      echo "</td>";
    }
    echo "</tr>";
  }

  echo "</td> </tr>";
  echo "</table >";

  //close the connection 
  odbc_close ($conn);
}
else echo "odbc not connected";
?>
Remember that 'myDSN' above is name of the DSN. Also note that you can change the table name from 'cars' to the name of your table and point the DSN to whatever database you like. One other thing to remember is that you can set up a DSN on your own machine though if you are using a hosting company you may have to ask the webmaster.
DSN-less connection
DSN-less connections don't require creation of system level DSNs for connecting to databases and provide an alternative to DSNs. We will now see how to connect to a database via PHP using Connection String in place of DSN name.
<?php

//create an instance of the  ADO connection object$conn = new COM ("ADODB.Connection")
  or die("Cannot start ADO");

//define connection string, specify database driver$connStr = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source= c:\inetpub\wwwroot\db\examples.mdb";
  $conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query = "SELECT * FROM cars";

//execute the SQL statement and return records
$rs = $conn->execute($query);

$num_columns = $rs->Fields->Count();
echo $num_columns . "<br>";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

echo "<table>";
while (!$rs->EOF)  //carry on looping through while there are records
{
    echo "<tr>";
    for ($i=0; $i < $num_columns; $i++) {
        echo "<td>" . $fld[$i]->value . "</td>";
    }
    echo "</tr>";
    $rs->MoveNext(); //move on to the next record
}


echo "</table>";

//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();

$rs = null;
$conn = null;
?>
READ MORE - DSN and DSN-less connections

PHP: Constants

Sweeps, Points, Prizes, Play! www.shopyourway.com. Need Help in Web Hosting, Domain, Website Builder, Email and Tools, SSl Certificate? Join with GoDaddy.com

Constants just as variables are used to store information. The main difference between constants and variables is that constant value can not be changed in the process of running program. It can be mathematic constants, passwords, paths to files, etc. By using a constant you "lock in" the value which prevents you from accidentally changing it. If you want to run a program several times using a different value each time, you do not need to search throughout the entire program and change the value at each instance. You only need to change it at the beginning of the program where you set the initial value for the constant.
Have a look at the example where we use the define function to set the initial value of a constant:
<?php
// first we define a constant PASSWORD
define("PASSWORD","admin");

echo (PASSWORD);                  // will display value of PASSWORD constant,  i.e. admin
echo constant("PASSWORD");   // will also display admin
echo "PASSWORD";                 // will display PASSWORD
?>
PHP also provides a number of built-in constants for you. "__FILE__", for example, returns the name of the file currently being read by the interpreter. "__LINE__" returns the line number of the file. These constants are useful for generating error messages. You can also find out which version of PHP is interpreting the script using the "PHP_VERSION" constant.
READ MORE - PHP: Constants

How to install and configure PHP 5 on Windows box

Sweeps, Points, Prizes, Play! www.shopyourway.com. Need Help in Web Hosting, Domain, Website Builder, Email and Tools, SSl Certificate? Join with GoDaddy.com

It is assumed that you have already successfully setup IIS or installed Apache on your machine and configured it. So, to configure PHP and secure its correct operation you need to go through a couple of steps.
Download and unzip the latest version of PHP
Download the latest zipped distribution of PHP from http://php.net. Unzip it. The recommendation is to put all the PHP stuff in a folder just off of the root drive (avoid whitespace), like C:\PHP.
Rename/copy php.ini-recommended to php.ini
In your PHP directory, you'll find a couple of php.ini-* files. They are pre-configured settings for a PHP install that you can use as an initial setup. The php.ini-recommended is the most secure, hence, the recommended one; just rename it to php.ini and copy to your Windows directory.
Create a session state directory and point the session.save_path variable in php.ini to it
This is optional, but recommended step. PHP does not need sessions, but it's something that will most likely be useful.
Create a session directory somewhere on the server. I created C:\PHP\sessionFolder. This directory will hold many small files with session variable information for PHP.
Now change the value of the session.save_path variable in php.ini to be the full path to that directory (session.save_path=C:\PHP\sessionFolder).
Setup the PHP extensions
You need to point PHP to the directory that holds the extension libraries and you need to uncomment the desired extensions.
  • Point PHP to the correct directory:
    Set extension_dir in php.ini to "C:\PHP\ext" (extension_dir = "C:\PHP\ext")
  • Uncomment the ones you want to use.
    It’s important to be sure that php_mysql.dll extension is uncommented (for PHP 5 or newer).
Make sure that PHP folder is in the system path
You should add "C:\PHP" to the server's PATH environment variable:
  • Right-click on My Computer, choose Properties
  • Flip to the Advanced tab
  • Click the Environment Variables button
  • Double-click the Path variable in the list of System variables.
  • Either add "C:\PHP;" to the beginning or ";C:\PHP" to the end (sans quotes, not both).
  • Restart IIS for it to take effect.
(To restart IIS you should right-click the local computer in the left pane of IIS Manager, click on All Tasks -> Restart IIS... -> OK)
Instead, you can copy all non-php dll files from C:\PHP to C:\Windows\System32 (or somewhere else in the server's PATH), but the first is the preferred method since it keeps the installation in one place, making upgrading or uninstalling easier.
 Configure IIS
For these steps, open IIS Manager
(Start -> Control Panel -> Administrative Tools -> Internet Information Services (IIS)  Manager).
Then add new extension (.php)
  • Expand the local computer in the left pane
  • Right-click on "Web Sites" in the left pane, then click "Properties" in the menu that pops up
  • Flip top the Home Directory tab
  • Click "Configuration"
  • Flip to the Mappings tab
  • Click Add...
  • Enter the full path to php5isapi.dll in the "Executable" textbox (Browse... to find it more easily if you need to)
  • Enter ".php" in the Extension textbox
  • Select radial button Limit to, enter "GET,POST,HEAD"
  • Click OK all the way out
This will apply to every website.
This sets up IIS to actually respond to requests for php files. Until now, IIS hadn't known what to do with php files, you just told it to pass them through php5isapi.dll.
Configure Apache Web Server
If you want PHP to work with your Apache server, you will need to modify your Apache configuration file to load it. There are two ways to configure Apache to use PHP: one is to configure it to load the PHP interpreter as an Apache module. The other is to configure it to run the PHP interpreter as a CGI binary. Unless you have a particular reason for running PHP as a CGI binary, you will probably want to load PHP as a module in Apache, since it runs more efficiently that way.
To configure Apache to load PHP as a module to parse your PHP scripts you should make some changes in the Apache configuration file, "httpd.conf", typically found in "c:\Program Files\Apache Group\Apache\conf\". It also can be accessed from your program files menu.
  • Search for the section that has a series of commented out "LoadModule" statements. Add the following line after all the LoadModule statements:
    LoadModule php5_module "c:/php/php5apache2.dll"
  • Search for "AddType" and add the following line after the last "AddType" statement:
    AddType application/x-httpd-php .php
If you need to support other file types, like ".php3" and ".phtml", simply add them to the list, like this:
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .phtml
Test your setup
Create a new file named test.php in one of the websites. Expand the Web Sites folder in the left pane of IIS Manager to see a list of existing websites. Right-click on a website -> Properties -> Home Directory -> Local Path will show you where the website root directory is.
Create test.php file with the following line: <?php phpinfo(); ?>
With your browser go to http://localhost/test.php
After loading test.php, you should see some information about your PHP installation. Be sure to scroll all the way down to the bottom to see that there were no errors. Pay attention to "Configuration File (php.ini) Path" field. Field's value is current location of php.ini file and you should make appropriate changes in it.
Date Settings (for PHP 5.1 or newer)
It is strongly recommended to configure date settings in php.ini. It is not safe to rely on the system's time zone settings.
Set date.timezone in php.ini to your time zone (in my example it's Europe/Moscow).
Complete list of Timezones you can see at http://php.net/manual/en/timezones.php
Location of libmysql.dll
Lastly, we need to be sure that copy of libmysql.dll is located in PHP folder (for PHP 5.0 or newer).
READ MORE - How to install and configure PHP 5 on Windows box

PHP: Multidimensional Arrays

Array does not have to be a simple list of keys and values; each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or three-dimensional array.
Two-dimensional Arrays
Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different - one of the ways to do it is using multidimensional arrays. The table below might represent our two-dimensional array. Each row represents a type of flower and each column – a certain attribute.
TitlePriceNumber
rose1.2515
daisy0.7525
orchid1.157
To store data in form of array represented by preceding example using PHP, let’s prepare the following code:
<?php
$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7)
             );
?>
This example shows that now $shop array, in fact, contains three arrays.  As you remember, to access data in one-dimensional array you have to point to array name and index. The same is true in regards to a two-dimensional array, with one exception: each element has two indexes – row and column.
To display elements of this array we could have organize manual access to each element or make it by putting For loop inside another For loop:
<?php
echo "<h1>Manual access to each element</h1>";

echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";

echo "<h1>Using loops to display array elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    for ($col = 0; $col < 3; $col++)
    {
        echo "<li>".$shop[$row][$col]."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>
Perhaps, instead of the column numbers you prefer to create their names. For this purpose, you can use associative arrays.  The following code will store the same set of flowers using column names:
<?php
$shop = array( array( Title => "rose",
                      Price => 1.25,
                      Number => 15
                    ),
               array( Title => "daisy",
                      Price => 0.75,
                      Number => 25,
                    ),
               array( Title => "orchid",
                      Price => 1.15,
                      Number => 7
                    )
             );
?>
It is easier to work with this array, in case you need to get a single value out of it. Necessary data can be easily found, if you turn to a proper cell using meaningful row and column names that bear logical content.  However, we are loosing the possibility to use simple for loop to view all columns consecutively.
You can view outer numerically indexed $shop array using the for loop. Each row of the $shop array is an associative array.  Hence, inside the for loop you need for each loop.  Also you can get each element from associative array manualy:
<?php
echo "<h1>Manual access to each element from associative array</h1>";

for ($row = 0; $row < 3; $row++)
{
    echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
    echo "<br />";
}

echo "<h1>Using foreach loop to display elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    foreach($shop[$row] as $key => $value)
    {
        echo "<li>".$value."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>
Three-dimensional Arrays
You don’t have to be limited by two dimensions: the same way as array elements can contain other arrays, these arrays, in their turn, can contain new arrays. 
Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine two-dimensional array as a table, then imagine a pile of such tables.  Each element can be referenced by its layer, row, and column.
If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional array. We can see from the code below, that three-dimensional array is an array containing array of arrays:
<?php
$shop = array(array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7)
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7)
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7)
                   )
             );
?>
As this array has only numeric indexes, we can use nested for loops to display it:
<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
    echo "<li>The layer number $layer";
    echo "<ul>";
 
    for ( $row = 0; $row < 3; $row++ )
    {
       echo "<li>The row number $row";
       echo "<ul>";
   
        for ( $col = 0; $col < 3; $col++ )
        {
            echo "<li>".$shop[$layer][$row][$col]."</li>";
        }
        echo "</ul>";
        echo "</li>";
    }
    echo "</ul>";
    echo "</li>";

echo "</ul>";
?>
This way of creating multidimensional arrays allows to create four- and five-dimensional arrays. Syntax rules do not limit the number of dimensions, but the majority of practical tasks logically correspond to the constructions of three or less dimensions.
READ MORE - PHP: Multidimensional Arrays

PHP: Variables

A variable is a holder for a type of data. So, based on its type, a variable can hold numbers, strings, booleans, objects, resources or it can be NULL. In PHP all the variables begin with a dollar sign "$" and the value can be assignes using the "=" operator. The dollar sign is not technically part of the variable name, but it is required as the first character for the PHP parser to recognize the variable as such.
Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't have to specify the variable type, as it takes the data type of the assigned value. The contents of a variable can be changed at any time, and so can its type. To declare a variable, you must include it in your script. You can declare a variable and assign it a value in the same statement.
Here is some code creating and assigning values to a couple of variables:
<?php
//Commented lines starting with the double
//forward slash will be ignored by PHP

//First we will declare a few variables
//and assign values to them


$myText = "Have a nice day!";
$myNum = 5;
//Note that myText is a string and myNum is numeric.

//Next we will display these to the user.

echo $myText;

//To concatenate strings in PHP, use the '.' (period) operator
echo "My favourite number is ". $myNum
?>
The output is: Have a nice day! My favourite number is 5.
Case Sensitivity
One thing that causes many problems and take hours of finding mistakes is case sensitivity. PHP is case sensitive. Have a look at the following code:
<?php
$myVar = "WebCheatSheet";
$myvar = "PHP tutorial";

echo "$myVar - $myvar"; //outputs "WebCheatSheet - PHP tutorial"
?>
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
  • PHP variables must start with a letter or underscore "_".
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores: $my_variable.
  • Variables with more than one word can also be distinguished with capitalization: $myVariable.
One important thing to note if you are coming from another programming language there is no size limit for variables.
Variable References
PHP also allows you to do some neat things with variables. It allows you to create aliases for variables, and it also allows you to have variables whose name is a variable. A variable reference, or alias, is a variable assigned to refer to the same information as another variable. To assign an alias to a variable, you use the reference operator, which is an equals sign followed by an ampersand. The following code snippet outputs 'Have a nice day!' twice:
<?php
$firstVar = 'nice day!';            //Assign the value 'nice day!' to $firstVar
$secondVar = &$firstVar;            // Reference $firstVar via $secondVar.
$secondVar = "Have a  $secondVar";  // Alter $secondVar...
echo $firstVar;
echo $secondVar;
?>
Environment Variables
Beyond the variables you declare in your code, PHP has a collection of environment variables, which are system defined variables that are accessible from anywhere inside the PHP code. All of these environment variables are stored by PHP as arrays. Some you can address directly by using the name of the index position as a variable name. Other can only be accessed through their arrays.
Some of the environment variables include:
$_SERVERContains information about the server and the HTTP connection. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).
$_COOKIEContains any cookie data sent back to the server from the client. Indexed by cookie name. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).
$_GETContains any information sent to the server as a search string as part of the URL. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
$_POSTContains any information sent to the server as a POST style posting from a client form. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).
$_FILEContains information about any uploaded files. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated).
$_ENVContains information about environmental variables on the server. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).
The code to use the environment variables will be as follows:
<?php
// moderate shortcut
$newVar = $_COOKIE["myFirstCookie"];

// full version
$newVar = $HTTP_COOKIE_VARS["myFirstCookie"];
?>
READ MORE - PHP: Variables

Looping Statements

In programming it is often necessary to repeat the same block of code a given number of times, or until a certain condition is met. This can be accomplished using looping statements. PHP has two major groups of looping statements: for and while. The For statements are best used when you want to perform a loop a specific number of times. The While statements are best used to perform a loop an undetermined number of times. In addition, you can use the Break and Continue statements within looping statements.
The While Loop
The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The While loop syntax is as follows:
while (condition)
{
  code to be executed;
}
The block of code associated with the While statement is always enclosed within the { opening and } closing brace symbols to tell PHP clearly which lines of code should be looped through.
While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:
while (there are still rows to read from a database)
{
   read in a row;
   move to the next row;
}
Let's have a look at the examples. The first example defines a loop that starts with i=0. The loop will continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop runs:
<?php
$i=0;
while ($i <= 10) { // Output values from 0 to 10
   echo "The number is ".$i."<br />";
   $i++;
}
?>
Now let's consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.
<?php

$month_array = array( "January", "February", "March", "April", "May", "June",
                      "July", "August", "September", "October", "November", "December");

echo "<select name=\"day\">";
$i = 1;
while ( $i <= 31 ) {
   echo "<option value=".$i.">".$i."</option>";
   $i++;
}
echo "</select>";

echo "<select name=\"month\">";
$i = 0;
while ( $i <= 11 ) {
   echo "<option value=".$i.">".$month_array[$i]."</option>";   
   $i++;
}
echo "</select>";

echo "<select name=\"year\">";
$i = 1900;
while ( $i <= 2007 ) {   
   echo "<option value=".$i.">".$i."</option>";   
   $i++;
}
echo "</select>";

?>
Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.
The Do...While Loop
The Do...While statements are similar to While statements, except that the condition is tested at the end of each iteration, rather than at the beginning. This means that the Do...While loop is guaranteed to run at least once. The Do...While loop syntax is as follows:
do
{
   code to be exected;
}
while (condition);
The example below will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than or equal to 10:
<?php
$i = 0;
do {
   echo "The number is ".$i."<br/>";
   $i++;
}
while ($i <= 10);
?>
The For Loop
The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 
for (initialization; condition; increment)
{
   code to be executed;
}
The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:
  • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
  • The update expression increment executes.
  • The statements execute, and control returns to step 2.
Have a look at the very simple example that prints out numbers from 0 to 10:
<?php
for ($i=0; $i <= 10; $i++)
{
   echo "The number is ".$i."<br />";
}
?>
Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:
<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";

for ($i = 1; $i <= 9; $i++ ) {   //this is the outer loop
  echo "<tr>";
  echo "<td>".$i."</td>";
 
   for ( $j = 2; $j <= 9; $j++ ) { // inner loop
        echo "<td>".$i * $j."</td>";
    }

   echo "</tr>";
}

echo "</table>";
?>
At last let's consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to add only the even numbers.
<?php
$total = 0;
$even = 0;

for ( $x = 1, $y = 1; $x <= 10; $x++, $y++ ) {
  if ( ( $y % 2 ) == 0 ) {
    $even = $even + $y;
  }
  $total = $total + $x;
}

echo "The total sum: ".$total."<br />";
echo "The sum of even values: ".$even;


?>
The Foreach Loop
The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as follows:
foreach (array as value)
{
   code to be executed;
}
   
foreach (array as key => value)
{
   code to be executed;
}
The example below demonstrates the Foreach loop that will print the values of the given array:
<?php
$email = array('john.smith@example.com', 'alex@example.com');
foreach ($email as $value) {
   echo "Processing ".$value."<br />";
}
?>
PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.
An alternative form of Foreach loop gives you access to the current key:
<?php
$person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
foreach ($person as $key => $value) {
   echo $key." is ".$value."<br />";
}
?>
In this case, the key for each element is placed in $key and the corresponding value is placed in $value.
The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the value of the variable $value can be manipulated but the original value of the array remains the same.
Break and Continue Statements
Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.
The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.
Examples below show how to use the Break statement:
<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) {
   if ($i==3){break;}
   echo "The number is ".$i;
   echo "<br />";
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {
  while ($j < 10) {
    if ($j == 5) {break 2;} // breaks out of two while loops
    $j++;
  }
  $i++;
}

echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>
The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:
<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) {
   if (i==3){continue;}
   echo "The number is ".$i;
   echo "<br />";
}
?>
READ MORE - Looping Statements
 

Most Reading

Diberdayakan oleh Blogger.