Apprendre php tutoriel 2
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.
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.
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 1Value is 2Value is 4Value is 3Value 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. It 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.
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.
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 −
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
NOTE − Built-in array functions is given in function reference PHP Array Functions
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 1Value is 2Value is 4Value is 3 Value is 5Value is twoValue is one Value is threeValue is fiveValue is four
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 2000Salary of qadir is 1000Salary of mohammad is highSalary of zara is 500Salary of zara is lowSalary of qadir is medium
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 - 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!\n
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 - Web Concepts
This session demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client browser can be redirected.
Identifying Browser & Platform
PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.
One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.
PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser.
Following example demonstrates how you can identify a client browser and operating system.
NOTE − The function preg_match()is discussed in PHP Regular expressionsession.
<html> <body> <?php function getBrowser() { $u_agent = $_SERVER['HTTP_USER_AGENT']; $bname = 'Unknown'; $platform = 'Unknown'; $version = ""; //First get the platform? if (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; }elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } // Next get the name of the useragent yes seperately and for good reason if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) { $bname = 'Internet Explorer'; $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $bname = 'Mozilla Firefox'; $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $bname = 'Google Chrome'; $ub = "Chrome"; }elseif(preg_match('/Safari/i',$u_agent)) { $bname = 'Apple Safari'; $ub = "Safari"; }elseif(preg_match('/Opera/i',$u_agent)) { $bname = 'Opera'; $ub = "Opera"; }elseif(preg_match('/Netscape/i',$u_agent)) { $bname = 'Netscape'; $ub = "Netscape"; } // finally get the correct version number $known = array('Version', $ub, 'other'); $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches['browser']); if ($i != 1) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){ $version= $matches['version'][0]; }else { $version= $matches['version'][1]; } }else { $version= $matches['version'][0]; } // check if we have a number if ($version == null || $version == "") {$version = "?";} return array( 'userAgent' => $u_agent, 'name' => $bname, 'version' => $version, 'platform' => $platform, 'pattern' => $pattern ); } // now try it $ua = getBrowser(); $yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent']; print_r($yourbrowser); ?> </body> </html>
This is producing following result on my machine. This result may be different for your computer depending on what you are using.
It will produce the following result −
Your browser: Google Chrome 54.0.2840.99 on windows reports: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Display Images Randomly
The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifies the seed number as its argument.
Following example demonstrates how you can display different image each time out of four images −
<html> <body> <?php srand( microtime() * 1000000 ); $num = rand( 1, 4 ); switch( $num ) { case 1: $image_file = "/php/images/logo.png"; break; case 2: $image_file = "/php/images/php.jpg"; break; case 3: $image_file = "/php/images/logo.png"; break; case 4: $image_file = "/php/images/php.jpg"; break; } echo "Random Image : <img src=$image_file />"; ?> </body> </html>
It will produce the following result −
Using HTML Forms
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.
Try out following example by putting the source code in test.php script.
<?php if( $_POST["name"] || $_POST["age"] ) { if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) { die ("invalid name and name should be alpha"); } echo "Welcome ". $_POST['name']. "<br />"; echo "You are ". $_POST['age']. " years old."; exit(); } ?> <html> <body> <form action = "<?php $_PHP_SELF ?>" method = "POST"> Name: <input type = "text" name = "name" /> Age: <input type = "text" name = "age" /> <input type = "submit" /> </form> </body> </html>
It will produce the following result −
- The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called and will produce following result −
- The method = "POST" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST chapter.
Browser Redirection
The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading.
The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.
Following example demonstrates how you can redirect a browser request to another web page. Try out this example by putting the source code in test.php script.
<?php if( $_POST["location"] ) { $location = $_POST["location"]; header( "Location:$location" ); exit(); } ?> <html> <body> <p>Choose a site to visit :</p> <form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST"> <select name = "location">. <option value = "http://www.tutorialspoint.com"> Tutorialspoint.com </option> <option value = "http://www.google.com"> Google Search Page </option> </select> <input type = "submit" /> </form> </body> </html>
It will produce the following result −
تعليقات
إرسال تعليق