Saturday 4 March 2017

PHP and MySql database connectivity Add,New,Edit,Delete,View options






------------------------------------------------------------ Table structure for table `players`

CREATE TABLE `players` (

`id` int(11) NOT NULL auto_increment,

`firstname` varchar(32) NOT NULL,

`lastname` varchar(32) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;



---------------------------------------------------------------Dumping data for table `players`

INSERT INTO `players` VALUES(1, 'Bob', 'Baker');

INSERT INTO `players` VALUES(2, 'Tim', 'Thomas');

INSERT INTO `players` VALUES(3, 'Rachel', 'Roberts');

INSERT INTO `players` VALUES(4, 'Sam', 'Smith');


----------------------------------------------------------------------------1) connect-db.php

<?php
/*
CONNECT-DB.PHP
Allows PHP to connect to your database
*/

// Database Variables (edit with your own server information)
$server = 'localhost';
$user = 'sateesh';
$pass = 'sateesh';
$db = 'sateesh';

// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>

--------------------------------------------------------------------------------------2)view.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM players")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td><a href="edit.php?id=' . $row['id'] . '">Edit</a></td>';
echo '<td><a href="delete.php?id=' . $row['id'] . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p><a href="new.php">Add a new record</a></p>
</body>
</html>

-----------------------------------------------------------------------------------3)delete.php
<?php
/*
DELETE.PHP
Deletes a specific entry from the 'players' table
*/
// connect to the database
include('connect-db.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];
// delete the entry
$result = mysql_query("DELETE FROM players WHERE id=$id")
or die(mysql_error());
// redirect back to the view page
header("Location: view.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: view.php");
}
?>

--------------------------------------------------------------------------------------4)edit.php
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $firstname, $lastname, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}







// connect to the database

include('connect-db.php');



// check if the form has been submitted. If it has, process the form and save it to the database

if (isset($_POST['submit']))

{

// confirm that the 'id' value is a valid integer before getting the form data

if (is_numeric($_POST['id']))

{

// get form data, making sure it is valid

$id = $_POST['id'];

$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));

$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));



// check that firstname/lastname fields are both filled in

if ($firstname == '' || $lastname == '')

{

// generate error message

$error = 'ERROR: Please fill in all required fields!';



//error, display form

renderForm($id, $firstname, $lastname, $error);

}

else

{

// save the data to the database

mysql_query("UPDATE players SET firstname='$firstname', lastname='$lastname' WHERE id='$id'")

or die(mysql_error());



// once saved, redirect back to the view page

header("Location: view.php");

}

}

else

{

// if the 'id' isn't valid, display an error

echo 'Error!';

}

}

else

// if the form hasn't been submitted, get the data from the db and display the form

{



// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)

if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)

{

// query db

$id = $_GET['id'];

$result = mysql_query("SELECT * FROM players WHERE id=$id")

or die(mysql_error());

$row = mysql_fetch_array($result);



// check that the 'id' matches up with a row in the databse

if($row)

{



// get data from db

$firstname = $row['firstname'];

$lastname = $row['lastname'];



// show form

renderForm($id, $firstname, $lastname, '');

}

else

// if no match, display result

{

echo "No results!";

}

}

else

// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error

{

echo 'Error!';

}

}

?>

-------------------------------------------------------------------------------------------5) new.php
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first, $last, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $first; ?>" /><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $last; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}









// connect to the database

include('connect-db.php');



// check if the form has been submitted. If it has, start to process the form and save it to the database

if (isset($_POST['submit']))

{

// get form data, making sure it is valid

$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));

$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));



// check to make sure both fields are entered

if ($firstname == '' || $lastname == '')

{

// generate error message

$error = 'ERROR: Please fill in all required fields!';



// if either field is blank, display the form again

renderForm($firstname, $lastname, $error);

}

else

{

// save the data to the database

mysql_query("INSERT players SET firstname='$firstname', lastname='$lastname'")

or die(mysql_error());



// once saved, redirect back to the view page

header("Location: view.php");

}

}

else

// if the form hasn't been submitted, display the form

{

renderForm('','','');

}

?>


----------------------------------------------------------------------------------6)view-paginated.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 3;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td><a href="edit.php?id=' . mysql_result($result, $i, 'id') . '">Edit</a></td>';
echo '<td><a href="delete.php?id=' . mysql_result($result, $i, 'id') . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p><a href="new.php">Add a new record</a></p>
</body>
</html>



Thursday 2 March 2017

PHP - Strings

They are sequences of characters, like "PHP supports string operations".
NOTE − Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<?php
   $variable = "name";
   $literally = 'My $variable will not print!\\n';
   
   print($literally);
   print "<br />";
   
   $literally = "My $variable will print!\\n";
   
   print($literally);
?>
This will produce the following result −
My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP −
  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are −
  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator −
<?php
   $string1="Hello World";
   $string2="1234";
   
   echo $string1 . " " . $string2;
?>
This will produce the following result −
Hello World 1234
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function

The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
   echo strlen("Hello world!");
?>
This will produce the following result −
12
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function

The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string −
<?php
   echo strpos("Hello world!","world");
?>
This will produce the following result −
 6
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

PHP - Arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.
<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>
This will produce the following result −
Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>
This will produce the following result −
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30, 
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>
This will produce the following result −
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP - Functions

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −
  • Creating a PHP Function
  • Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −
<html>
   
   <head>
      <title>Writing PHP Function</title>
   </head>
   
   <body>
      
      <?php
         /* Defining a PHP Function */
         function writeMessage() {
            echo "You are really a nice person, Have a nice time!";
         }
         
         /* Calling a PHP Function */
         writeMessage();
      ?>
      
   </body>
</html>
This will display following result −
You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
<html>
   
   <head>
      <title>Writing PHP Function with Parameters</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            echo "Sum of the two numbers is : $sum";
         }
         
         addFunction(10, 20);
      ?>
      
   </body>
</html>
This will display following result −
Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>
   
   <head>
      <title>Passing Argument by Reference</title>
   </head>
   
   <body>
      
      <?php
         function addFive($num) {
            $num += 5;
         }
         
         function addSix(&$num) {
            $num += 6;
         }
         
         $orignum = 10;
         addFive( $orignum );
         
         echo "Original Value is $orignum<br />";
         
         addSix( $orignum );
         echo "Original Value is $orignum<br />";
      ?>
      
   </body>
</html>
This will display following result −
Original Value is 10
Original Value is 16 

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            return $sum;
         }
         $return_value = addFunction(10, 20);
         
         echo "Returned value from the function : $return_value";
      ?>
      
   </body>
</html>
This will display following result −
Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
      
      <?php
         function printMe($param = NULL) {
            print $param;
         }
         
         printMe("This is test");
         printMe();
      ?>
      
   </body>
</html>
This will produce following result −
This is test

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
<html>
   
   <head>
      <title>Dynamic Function Calls</title>
   </head>
   
   <body>
      
      <?php
         function sayHello() {
            echo "Hello<br />";
         }
         
         $function_holder = "sayHello";
         $function_holder();
      ?>
      
   </body>
</html>
This will display following result −
Hello

Flow Control Structures in PHP


PHP - Decision Making

The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions. PHP supports following three decision making statements −
Decision making statements in PHP
  • if...else statement − use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
  • elseif statement − is used with the if...else statement to execute a set of code if one of the several condition is true
  • switch statement − is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.

The If...Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

Syntax

if (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, Otherwise, it will output "Have a nice day!":
<html>
   <body>
   
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!"; 
         
         else
            echo "Have a nice day!"; 
      ?>
   
   </body>
</html>
It will produce the following result −
Have a nice day!

The ElseIf Statement

If you want to execute some code if one of the several conditions are true use the elseif statement

Syntax

if (condition)
   code to be executed if condition is true;
elseif (condition)
   code to be executed if condition is true;
else
   code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise, it will output "Have a nice day!" −
<html>
   <body>
   
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!";
         
         elseif ($d == "Sun")
            echo "Have a nice Sunday!"; 
         
         else
            echo "Have a nice day!"; 
      ?>
      
   </body>
</html>
It will produce the following result −
Have a nice day!

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression){
   case label1:
      code to be executed if expression = label1;
      break;  
   
   case label2:
      code to be executed if expression = label2;
      break;
      default:
   
   code to be executed
   if expression is different 
   from both label1 and label2;
}

Example

The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lable matches then statement will execute any specified default code.
<html>
   <body>
      
      <?php
         $d = date("D");
         
         switch ($d){
            case "Mon":
               echo "Today is Monday";
               break;
            
            case "Tue":
               echo "Today is Tuesday";
               break;
            
            case "Wed":
               echo "Today is Wednesday";
               break;
            
            case "Thu":
               echo "Today is Thursday";
               break;
            
            case "Fri":
               echo "Today is Friday";
               break;
            
            case "Sat":
               echo "Today is Saturday";
               break;
            
            case "Sun":
               echo "Today is Sunday";
               break;
            
            default:
               echo "Wonder which day is this ?";
         }
      ?>
      
   </body>
</html>
It will produce the following result −
Today is Monday
 

PHP - Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for − loops through a block of code a specified number of times.
  • while − loops through a block of code if and as long as a specified condition is true.
  • do...while − loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach − loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.
for loop in Php

Syntax

for (initialization; condition; increment){
   code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −
<html>
   <body>
      
      <?php
         $a = 0;
         $b = 0;
         
         for( $i = 0; $i<5; $i++ ) {
            $a += 10;
            $b += 5;
         }
         
         echo ("At the end of the loop a = $a and b = $b" );
      ?>
   
   </body>
</html>
This will produce the following result −
At the end of the loop a = 50 and b = 25

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
for loop in PHP

Syntax

while (condition) {
   code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
   <body>
   
      <?php
         $i = 0;
         $num = 50;
         
         while( $i < 10) {
            $num--;
            $i++;
         }
         
         echo ("Loop stopped at i = $i and num = $num" );
      ?>
      
   </body>
</html>
This will produce the following result −
Loop stopped at i = 10 and num = 40 

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do {
   code to be executed;
}
while (condition);

Example

The following example 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 10 −
<html>
   <body>
   
      <?php
         $i = 0;
         $num = 0;
         
         do {
            $i++;
         }
         
         while( $i < 10 );
         echo ("Loop stopped at i = $i" );
      ?>
      
   </body>
</html>
This will produce the following result −
Loop stopped at i = 10

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value) {
   code to be executed;
}

Example

Try out following example to list out the values of an array.
<html>
   <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
PHP Break Statement

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
   <body>
   
      <?php
         $i = 0;
         
         while( $i < 10) {
            $i++;
            if( $i == 3 )break;
         }
         echo ("Loop stopped at i = $i" );
      ?>
   
   </body>
</html>
This will produce the following result −
Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.
PHP Continue Statement

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
<html>
   <body>
   
      <?php
         $array = array( 1, 2, 3, 4, 5);
         
         foreach( $array as $value ) {
            if( $value == 3 )continue;
            echo "Value is $value <br />";
         }
      ?>
   
   </body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 4
Value is 5 

Operators and Expressions

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.
  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by de-numerator
B / A will give 2
%
Modulus Operator and remainder of after an integer division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9
Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
Operator
Description
Example
and
Called Logical AND operator. If both the operands are true then condition becomes true.
(A and B) is true.
or
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A or B) is true.
&&
Called Logical AND operator. If both the operands are non zero then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false.
Assignment Operators
There are following assignment operators supported by PHP language −
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −
Operator
Description
Example
? :
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
Operators Categories
All the operators we have discussed above can be categorised into following categories −
  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Unary
! ++ --
Right to left
Multiplicative
* / %
Left to right
Additive
+ -
Left to right
Relational
< <= > >=
Left to right
Equality
== !=
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %=
Right to left