PHP Looping
Looping statements in PHP are used to execute the same block of code a specified number of times.
Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.In PHP we have the following looping statements:
- 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
- for - loops through a block of code a specified number of times
- foreach - loops through a block of code for each element in an array
The while Statement
The while statement will execute a block of code if and as long as a condition is true.Syntax
while (condition) code to be executed; |
Example
The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:<html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> |
The do...while 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 5:<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html> |
The for Statement
The for statement is the most advanced of the loops in PHP.In it's simplest form, the for statement is used when you know how many times you want to execute a statement or a list of statements.
Syntax
for (init; cond; incr) { code to be executed; } |
- init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement.
- cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends.
- incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.
- cond: All expressions separated by a comma are evaluated but the result is taken from the last part. This parameter being empty means the loop should be run indefinitely. This is useful when using a conditional break statement inside the loop for ending the loop.
Example
The following example prints the text "Hello World!" five times:<html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html> |
The foreach Statement
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 $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html> |
PHP Functions
The real power of PHP comes from its functions.
In PHP - there are more than 700 built-in functions available.
PHP Functions
In this tutorial we will show you how to create your own functions.For a reference and examples of the built-in functions, please visit our PHP Reference.
Create a PHP Function
A function is a block of code that can be executed whenever we need it.Creating PHP functions:
- All functions start with the word "function()"
- Name the function - It should be possible to understand what the function does by its art with a letter or underscore (not a number)
- Add a "{" - The function code starts after the opening curly brace
- Insert the function code
- Add a "}" - The function is finished by a closing curly brace
Example
A simple function that writes my name when it is called:<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } writeMyName(); ?> </body> </html> |
Use a PHP Function
Now we will use the function in a PHP script:<html> <body> <?php function writeMyName() { echo "Kai Jim Refsnes"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html> |
The output of the code above will be:
Hello world! My name is Kai Jim Refsnes. That's right, Kai Jim Refsnes is my name. |
PHP Functions - Adding parameters
Our first function (writeMyName()) is a very simple function. It only writes a static string.To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:<html> <body> <?php function writeMyName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeMyName("Kai Jim"); echo "My name is "; writeMyName("Hege"); echo "My name is "; writeMyName("Stale"); ?> </body> </html> |
My name is Kai Jim Refsnes. My name is Hege Refsnes. My name is Stale Refsnes. |
Example 2
The following function has two parameters:<html> <body> <?php function writeMyName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is "; writeMyName("Kai Jim","."); echo "My name is "; writeMyName("Hege","!"); echo "My name is "; writeMyName("Ståle","..."); ?> </body> </html> |
My name is Kai Jim Refsnes. My name is Hege Refsnes! My name is Ståle Refsnes... |
PHP Functions - Return values
Functions can also be used to return values.Example
<html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> |
1 + 16 = 17 |
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.Form example:
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> |
The "welcome.php" file looks like this:
<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> |
Welcome John. You are 28 years old. |
Form Validation
User input should be validated whenever possible. Client side validation is faster, and will reduce server load. However, any site that gets enough traffic to worry about server resources, may also need to worry about site security. You should always use server side validation if the form accesses a database.
A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
PHP $_GET
The $_GET variable is used to collect values from a form with method="get".
The $_GET Variable
The $_GET variable is an array of variable names and values sent by the HTTP GET method.The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).
Example
<form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> |
http://www.w3schools.com/welcome.php?name=Peter&age=37 |
Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! |
Why use $_GET?
Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old! |
PHP $_POST
The $_POST variable is used to collect values from a form with method="post".
The $_POST Variable
The $_POST variable is an array of variable names and values sent by the HTTP POST method.The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Note: There is an 8 Mb max size for the POST method by default. This can be changed by setting the post_max_size in the php.ini file.
Example
<form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> |
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! |
Why use $_POST?
- Variables sent with HTTP POST are not shown in the URL
- Variables have no length limit
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old! |
PHP Date()
The PHP date() function is used to format a time or a date.
The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.Syntax
date(format,timestamp) |
Parameter | Description |
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time (as a timestamp) |
PHP Date - What is a Timestamp?
A timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.PHP Date - Format the Date
The first parameter in the date() function specifies how to format the date/time. It uses letters to represent date and time formats. Here are some of the letters that can be used:- d - The day of the month (01-31)
- m - The current month, as a number (01-12)
- Y - The current year in four digits
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:
<?php echo date("Y/m/d"); echo "<br />"; echo date("Y.m.d"); echo "<br />"; echo date("Y-m-d"); ?> |
2006/07/11 2006.07.11 2006-07-11 |
PHP Date - Adding a Timestamp
The second parameter in the date() function specifies a timestamp. This parameter is optional. If you do not supply a timestamp, the current time will be used.In our next example we will use the mktime() function to create a timestamp for tomorrow.
The mktime() function returns the Unix timestamp for a specified date.
Syntax
mktime(hour,minute,second,month,day,year,is_dst) |
<?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow); ?> |
Tomorrow is 2006/07/12 |
No comments:
Post a Comment