Please style sheet are not equal in internet explorer browser Firefox, Chrome, Safari, Apple and Opera browser please visit this website.

Thank for Visit My Site and Please sent me Shayari, Status and Quotes post request.

PHP - PHP Flow control and looping, PHP Functions

PHP Flow control and looping
 
IF-ELSE
 
The PHP If Statement
 
The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occurring every year on January 1st.
 
This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.
 
If Statement Example
 
IF (conditional statement) {
  [code if condition is true]
}
 
The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.
 
PHP Code:
 
<?php
$my_name = "phpguy";

if ( $my_name == "phpguy" ) {
 echo "Your name is phpguy!<br />";
}
echo "Welcome to MKDTutorials Education!";
?>
 
Display:
 
Your name is phpguy!
Welcome to MKDTutorials Education!
 
Did you get that we were comparing the variable $my_name with "phpguy" to see if they were equal? In PHP you use the double equal sign (==) to compare values. In addition, notice that because the if statement turned out to be true, the code segment was executed, printing out "Your name is phpguy!".
 
Let's go a bit more in-depth into this example to iron out the details.
 
. We first set the variable $my_name equal to "phpguy".

. We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "phpguy"

. The comparison between $my_name and "phpguy" was done with a double equal sign "==", not a single equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.

. Translated into english the PHP statement ( $my_name == "phpguy" ) is ( $my_name is equal to "phpguy" ).

. $my_name is indeed equal to "phpguy" so the echo statement is executed.
 
A False If Statement
 
Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:
 
PHP Code:
 
<?php
$my_name = "LAMPGuy";

if ( $my_name == "phpguy" ) {
 echo "Your name is phpguy!<br />";
}
echo "Welcome to MKDTutorials Education!";
?>

 
Display:
 
Welcome to MKDTutorials Education!
 
Here the variable contained the value "LAMPGuy", which is not equal to "phpguy". The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal!
 
IF.. ELSE statement
 
IF..ELSE is used in PHP to provide conditional judgements.
 
The basic syntax is as follows:
 
IF (conditional statement) {
  [code if condition is true]
}
ELSE {
  [code if condition is false]
}
 
Let's see an example. Assuming we have the following piece of code:
 
$num = 7;
IF ($num > 5) {
  print "Number is greater than 5";
}
ELSE {
  print "Number is less than 5";
}
 
The output of the above code is:
 
Number is greater than 5
 
This is because the condition, ($num > 5), is true. Therefore, the code in the bracket after IF is executed.
 
 
 
Switch-case
 
The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. SWITCH is used in PHP to replace nested IF..ELSE loops, and is similar to the CASE command in other computer languages.
 
With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!
 
The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.
 
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:
 
<?php
$day=1;


switch($day)
{
 case 1:
   echo "<today is <b>Monday</b>";
 break;
 case 2:
   echo "Today is <b>Tuesday</b>";
 break;
 default:
  echo "<b>Invalid Day Number ".$day."</b>";
}

?>
 
Type the above code and save it as switch-case.php and open the page in browser to view the output.
 
 
 
PHP Loops
 
It is generally accepted that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowledge that computers really don't do anything unless someone programs them to tell them what to do.
 
Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met. This is where for, while and do ... while loops are of use.
 
Note: if you have any kind of programming experience, you won't have any problem with PHP either. Loops and Conditional statements are same in PHP as they are found in other programming languages, such as C/C++/Java/ any other.
 
For loop
 
Suppose you wanted to add a number to itself ten times. One way to do this might be to write the following PHP script:
 
<?php
$var = 10;

$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;
$var += $var;

?>
 
Whilst this is somewhat ungainly and time consuming to type, it does work. What would happen, however, if there was a requirement to perform this task 100 times or even 10,000 times. Writing a script to perform this as above would be prohibitively time consuming. This is exactly the situation the for loop is intended to handle.
 
The syntax of a PHP for loop is as follows:
 
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
      // PHP statements to be executed go here
}
 
The initializer typically initializes a counter variable. Traditionally the variable $i is used for this purpose.
 
For example:
 
$i = 0
 
which sets the counter to be the value $i and sets it to zero. The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times.
 
For example, if we want to loop 1000 times:

$i < 1000

Finally, the loop expression specifies the action to perform on the counter variable.

For example to increment by 1: $i++

Bringing this all together we can create a for loop to perform the task outlined in the earlier in this section:
 
<?php
$j = 10;

for ($i=0; $i<10; $i++)
{
      $j += $j;
}
echo $j;
?>
 
Output:
 
10240
 
As with the if statement, the enclosing braces are optional if a single line of script is to be executed, but their use is strongly recommended.
 
While loop
 
The PHP for loop described previously works well when you know in advance how many times a particular task needs to be repeated in a script. Clearly, there will frequently be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this PHP, provides the while loop. Essentially, the while loop repeats a set of tasks until a specified condition is met.
 
The while loop syntax is defined follows:
 
<?php
while (''condition'')
{
      // PHP statements go here
}
?>
 
where condition is an expression that will return either true or false and the // PHP statements go here comment represents the PHP to be executed while the expression is true.
 
For example:
 
<?php
$mycount=0;
$j=1;
while ( $myCount < 100 )
{
      $myCount = $myCount + $j;
     echo "<br>".$myCount;
}
?>
 
Output:
Try it yourself
 
In the above example the while expression will evaluate whether $myCount is less than 100. If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks. If $myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of $myCount. This process repeats until $myCount is greater than 100, at which point the loop exits.
 
Do-while loop
 
You can think of the do ... while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed.
 
The do .. while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need.
 
The syntax for the do ... while loop is as follows:
 
<?php
do
{
       ''PHP statements''
} while (''conditional expression'')
?>
 
In the do ... while example below the loop will continue until $i equals 0:
 
<?php
$i = 10;
do
{
       $i--;
} while ($i > 0);
?>
 
Foreach loop
 
The foreach statement is used to loop through arrays.

For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.
 
Syntax:
 
foreach (array as value)
{
code to be executed;
}
 
Example
 
The following example demonstrates a loop that will print the values of the given array:
 
<html>
<body>
<?php
$city=array("Noida", "Ambikapur", "Banglore");
echo "<h3>Foreach Demo</h3><hr width= \"80%\">";
$num=0;
foreach ($city as $value)
{
 $num+=1;
  echo "City $num: " . $value . "<br />";
}
echo "<hr width=\"80%\">";
?>
</body>
</html>
 
Type the above code and save it as foreach.php and open the script in browser to view the output.
 
img
 
Assignment:
 
1. Write a PHP script to print a countdown (10,9.. ..1).
2. Write a PHP Script to print Square of all numbers from 1-10 using loop.
3. Write a PHP script to print Square of all even numbers between 1-20.
 
 
 
PHP Functions
 
PHP Functions
 
In the world of programming and scripting there are two ways to write code. One way is to write long, sprawling and monolithic sections of script. Another is to break the scripts up into tidy, self contained modules that can be re-used without having to re-invent the same code over and over again.
 
Obviously the latter is highly preferable to the former, and the fundamental building block of this approach to writing PHP scripts is the function.
 
Similar to other programming languages, such as C/C++/Java/JavaScript/etc., PHP provides a way for programmers to define functions, which can then be called elsewhere in the program.
 
A function is a block of code that can be executed whenever we need it. A function is just a name we give to a block of code that can be executed when needed
 
Functions are basically named scripts that can be called upon from any other script to perform a specifc task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.
 
PHP functions exist it two forms, functions that are provided with PHP to make your life as a web develeper easier, and those that you as a web developer create yourself.
 
 
 
Creating and using simple functions
 
The first step in creating a PHP function is provide a name by which you will reference the function. Naming conventions for PHP functions are the same as those for variables in that they must begin with a letter or an underscore and must be devoid of any kind of white space or punctuation. You must also take care to ensure that your function name does not conflict with any of the PHP built in functions.
 
PHP functions are created using the function keyword followed by the name and, finally, a set of parentheses. The body of the function (the script that performs the work of the function) is then enclosed in opening and closing braces.
 
The following example function simply outputs a string when it is called:
 
<?php
function sayHello()
{
       print "Hello";
}
?>
<hr>
<center><h3>PHP Function Demo</h3></center>
<hr>
<?php
sayHello();
?>

 
Save the above script as simplefunction.php and open the page in browser to view the output.
 
img
 
 
 
Passing Parameters to a Functions
 
Parameters (or arguments as they are more frequently known) can be passed into a function. There are no significant restrictions of the number of arguments which can be passed through to the function. A function can be designed to accept parameters by placing the parameter names inside the parentheses of the function definition.
 
Those variables can then be accessed from within the function body as follows:
 
<HTML>
<HEAD>
<TITLE>PHP Function: Passing Parameter
</TITLE></HEAD>
<BODY>
<?php
function sum ($val1, $val2)
{
 $result=$val1+$val2;
     echo $result;
}
?>
<hr>
 <CENTER><H3>PHP Function: Passing Parameter</H3></CENTER>
<hr>
<p>Sum of 21 and 79 =<?php sum(21,79);?></p>
</BODY>
</HTML>
 
Type the above script and save it as function-parameter.php and open the page in the browser to view the output.
 
img
 
In the above example the sum () function accepts two parameters as arguments, adds them together and returns the result.
 
 
 
Returning values from function
 
A single value may be returned from a PHP function to the script from which it was called. The returned value can be any variable type of your choice.
 
Besides being able to pass functions information, you can also have them return a value. However, a function can only return one thing, although that thing can be any integer, float, array, string, etc. that you choose!
 
How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function.
 
Something like:
 
. $myVar = somefunction();

Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers.
 
The return keyword is used to return the value:
 
<HTML>
<HEAD>
<TITLE>PHP Function: Returning Values
</TITLE></HEAD>
<BODY>
<?php
function sum ($val1, $val2)
{
 $result=$val1+$val2;
    return $result;
}
?>
<hr>
 <CENTER><H3>PHP Function: Returning Values</H3></CENTER>
<hr>
<p>Sum of 21 and 79 =<?php echo " ".sum(21,79);?></p>
</BODY>
</HTML>
 
The above example returns the value of 100 to the calling script.
 
 
 
Built-in Functions
 
Like any other programming language, PHP offers several built-in function for day-to-day use in your coding. Most of these functions are very helpful in achieving your programming goals and are well documented.
 
Some (not even most) usage of built-in functions are as mentioned below:
 
. Converting a string of letters to uppercase and lowercase

. Displaying and using the date and time

. Initializing and closing a database connection

. Declaring and using an array

. Handling files

. Accessing data in forms

. Filesystem Functions

. Function to open FTP connections

. Email related functions

. Mathematical Functions

. MySQL specific functions

. URL Functions
 
For complete list of built-in PHP functions please visit
 
http://us2.php.net/quickref.php .
 
 
 
File inclusion functions
 
include function
 
INCLUDE is used in PHP to append the code from an external file into the current file.
 
The syntax for INCLUDE is
 
INCLUDE ("external_file_name");
 
This is a convenient feature for a large website. Often, we may want to change an element of the website that is consistent across the entire site, yet we don't want to go through the trouble of updating every single file. In this case, we can simply use INCLUDE in every file to call the same external file, and then all we need to change is the content in that one external file.
 
Let's look at a simple example.
 
Assuming we have the following three files:
 
main.php
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP Include</title>
</head>

<body>
<table width="100%" border="0" cellspacing="3" cellpadding="0">
  <tr>
    <td width="18%"> </td>
    <td width="72%"> </td>
    <td width="10%" rowspan="2"> </td>
  </tr>
  <tr>
    <td rowspan="2"><?php
    include ("menu.php");
    ?>
    </td>
    <td><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR></td>
  </tr>

  <tr>

  <?php
  #Footer
  include ("footer.php");
  ?>

    <td> </td>
  </tr>
</table>
</body>
</html>
 
2. menu.php
 
<?php
#External PHP Menu
?>
<table width="100%" border="0" cellspacing="3" cellpadding="0">
  <tr>
    <td><A HREF="http://www.mkdtutorials.com">MKDTutorials.com Home</A></td>
  </tr>
  <tr>
    <td><A HREF="http://education.mkdtutorials.com">MKDTutorials Education</A></td>
  </tr>
  <tr>
    <td><A HREF="http://mail.mkdtutorials.com">Mail</A></td>
  </tr>
  <tr>
    <td><A HREF="mailto:support@mkdtutorials.com">Contact US</A></td>
  </tr>
</table>
 
3. Footer.php
 
<td style="background-color:#0099FF; text-align:center">
<p style=" font-family:Verdana, Arial, Helvetica, sans-serif; color:#ffccFF; size:14; font-weight:700">© MKDTutorials.com Pvt. Ltd.</p></td>
 
Upon executing main.php, we'll get the following output:
 
img
 
This is because, to the web server, it sees these three scripts as single script.
 
require function
 
Both include & require constructs are identical in every way except how they handle failure. include() produces a Warning on the other hand require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page and use include otherwise.
 
Syntax:
 
require ("external_file");
 
We can use require in our previous example in place of include or vice versa.
 
Now, suppose we are using require instead of include to include menu.php and we misspelled its name as meno.php, then it will produce the following error:
 
<?php
    require ("meno.php");
 ?>

img
 
include_once and require_once functions
 
include_once
 
The behavior of include_once is similar to the include () statement, that is, include_once() statement includes and evaluates the specified file during the execution of the script. The difference being that if the code from a file has already been included, include_once will not be included again. As the name suggests, it will be included just once.
 
require_once
 
The require_once() statement includes and evaluates the specified file during the execution of the script. The only difference between require & require_once is that if the code from a file has already been included, it will not be included again.
 
Assignment
 
1. Create a Multi file [at least 5(1 main 4 sub)] PHP script and use all file inclusion functions to include them to main script.

2. Write a PHP script to print a countdown (10,9.. ..1) using function.

3. Write a PHP Script to print Square of all numbers from 1-10 using loop using function.

4. Write a PHP function to calculate and return sum of all even numbers between 1-50.
Remember function should not print the output by itself, rather it should return a value.

5. Create a function hello which accepts name as argument and print "Hello XYZ", where XYZ is the value of the argument passed to the function.
 
 
 

SHARE THIS PAGE

0 Comments:

Post a Comment

Circle Me On Google Plus

Subject

Follow Us