PHP Basic
From w3cyberlearnings
Back to Learning PHP
- PHP basic provides the foundation for you to start familiar with PHP.
- Learn the PHP functions and rules.
- Develop a simple web application.
- When you have finished the PHP basic tutorial, you can expose to other PHP tutorials for more.
- This tutorial is the step by step for someone to refresh his or her programming language in PHP.
- If you want to learn how to create web application in PHP, you can browse the PHP category.
PHP Installation
- LAMP (Linux, Apache, MySQL, and PHP) is a package for web development.
- Linux is the open source operating system, and in this tutorial we use Ubuntu Linux.
- Apache is the web server uses to run the PHP program, and it is also installed in the Ubuntu Linux.
- Finally, we need MySQL for database storage.
Install on Ubuntu Linux
$sudo apt-get install apache2 $sudo apt-get install php5 $sudo apt-get install libapache2-mod-php5 $sudo apt-get install mysql-server $sudo apt-get install php5-mysql
Install in Ubuntu Linux using Synaptic Package Manager
- You need the root or privilege user password to use Synaptic Package Manager.
- Synaptic Package Manager allow you to install software from the repository, and it is easy and fast.
- When you are in the Synaptic Package Manager, you can search a specific software to install, or to remove a software that you have already installed.
- Following the following step to go and open Synaptic Package Manager:
->System->Administration->Synaptic Package Manager
Install on Microsoft Windows or Linux
- This bundle package included MySQL, Apache, and PHP.
- You can download this package and install either on Linux, Microsoft Windows, or Mac.
- Install Apache,MySQL, PHP on Windows:WAMP
- Install Apache, MySQL, PHP on Linux XAMPP
Install PHP Editor
- You can use notepad to write your PHP program. However, this is not a good option.
- If you in Linux, you can use vi or vim, but it is not recommended as well.
- Free PHP editor are Eclipe IDE, Notepad++ and NetBean, and these editors are very powerful and easy to use.
It helps you to develop the application faster.
- Eclipse IDE and Netbean IDE allow you to setup the project according to your need. You can setup the project remotely using FTP and develop your application within your desktop environment.
- http://notepad-plus-plus.org/ Notepad++
- http://www.eclipse.org/downloads/ Eclipse
- http://netbeans.org/ Netbeans
PHP Syntax
- All php programs start with <?php and end with ?>, and between the start and end block is the PHP program.
- PHP program has the .php extension.
- Example: myphppage.php.
<?php /// your php code is place here ?>
Code (myfirstPHP.php)
- You can included PHP program in HTML page.
- In this simple PHP program, the PHP program included in the HTML page.
<html> <head> <title>First PHP file</title> </head> <body> <?php echo "Hello World <br/>"; echo "Start to learn PHP from a very basic <br/>"; ?> </body> </html>
Result for myfirstPHP.php
Hello World Start to learn PHP from a very basic
PHP Block
- PHP program can be developed without placing within the HTML page.
- In this tutorial, the PHP program places within the PHP block.
<?php echo "Hello World <br/>"; echo "Start to learn PHP from a very basic <br/>"; ?>
PHP Class and Object-Oriented Example
- PHP supports object-oriented programming language and concepts.
- A car can be an object and person can be an object as well.
- Define you program into object make its easy to design and easy to modify.
- A car object or a person object can be modified from the object level.
- In PHP, we use class to define an object.
- PHP class can have multiple properties and methods.
- Example for the properties of the car object: Door, Color, Machine Type, and many other components
- The class properties use to define the class attributes.
- Example for the car methods: run, start, stop, add gas, add components, remove
- The class methods use to define the function of the class.
- PHP class can be related, and this relationship called parent and child relationship.
- When a PHP class has the relationship with another PHP class, we make the class to share some properties and methods.
- To create an object: class ObjectName{}
- In this example, we created a PHP class called sampleClass, and this class has a constructor method and a saySomething() method.
- We create or assign the sampleClass to the $sample1.
Code (sampleClass.php)
<?php class sampleClass { public $my_world; public function __construct() { echo "Calling class constructor <br/>"; } public function saySomething() { echo "Joke and Jike are my ". $this->my_world . "<br/>"; } } $sample1 = new sampleClass(); $sample1->my_world = "best friend"; $sample1->saySomething(); ?>
Result for sampleClass.php
Calling class constructor Joke and Jike are my best friend
PHP Comments
- There are single line comment and multiple line comment.
- A single line comment can be created in two ways, and a multiple lines comment can only create in one way.
Single line comments
<?php // single line comment, with double back slash. $_variable = "Good old day"; echo $_variable . "<br/>"; # single line comment with a pound sign $_studentTest = "Hello World"; echo $_studentTest . "<br/>"; ?>
Multiple Lines Comment
- Multiple line comments begin with /* and end with */,
- The text within the /* text */, and these texts will be ignored by PHP program.
<?php /* multiple line comments this is multiple comments id contains 5 digits name is a full name */ $id = 54232; $name = 'Bob Maat'; ?>
PHP Echo
- The echo function is slightly faster than the print function.
- We use the echo function to print out information to the screen.
Code (myEcho.php)
<?php $message = 'Good day everyone!'; echo "Hello php tutorial<br/>"; echo "w3cyberlearning.com". "<br/>"; echo $message. "<br/>"; ?>
Display Result
Hello php tutorial w3cyberlearning.com Good day everyone!
Code (myEcho2.php)
- We use parentheses to group number together for calculation.
- Without the parentheses we will not get a correct result.
<?php $number = 200; echo "Cost is ", $number; echo "<br/>"; echo "Cost is ". ($number + 104); ?>
Display Result
Cost is 200 Cost is 304
Use echo function between HTML script
- We create two variables: $title and $message.
- At the top of the page, we have initialized these two variables' value.
- In the HTML body, we create PHP block to display the $title and $message respectively.
Code (echo3.php)
<?php $title = "PHP tutorial for beginner"; $message =<<<HMM We learn together and we make mistake together. If you have any question, please let me know. HMM; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <H3><?php echo $title; ?></H3> <p> <?php echo $message; ?> </p> </body> </html>
Display Result
PHP tutorial for beginner We learn together and we make mistake together. If you have any question, please let me know.
PHP Print
- print is similar to the echo, but it is not a real function.
- So that you are not need to use the parentheses with its argument list.
print "good old day";
PHP Operators
- We use the comparison operator to compare two values.
- The result of the comparison operator can be false or true.
Operator Description Example Result != Not Equal To $x != $y true <> Not Equal To $x <> $y true == Equal To $x == $y false < Less Than $x < $y true > Greater Than $x > $y false <= Less Than or Equal To $x <= $y true >= Greater Than or Equal To $x >= $y false
Arithmetic Operator
Let $x = 8 and $y = 3 Operator Description Example Result - Negation -$x -8 + Addition $x + $y 11 - Substraction $x - $y 5 * Multiplication $x * $y 24 / Division $x / $y 2.6667 % Modulus $x % $y 2
Assignment Operators
Lex $x = 20 and $y = 10 Example Description Result $x = $y Assign $y to $x, $x is equal to $y 10 $x = $y * 2 $x = 10 * 2 20 $x += $y $x = $x + $y 30 $x = ($x = 3) + 3 within the parentheses $x is equal to 3, and 3+3 is equal to 6 6 $x = "hello world" Re-assign the $x to a string hello world $x = "hello world ".$y concatenate a string Using period hello world 10
PHP Variables
- PHP variable name starts with a dollar sign "$", and the variable value can be integer, double, or string.
Variable is case sensitive Variable must start with dollar sign Variable can start with underscore "_" Variable can separated with an underscore
PHP Syntax
$variable = VALUE;
PHP Valid Variables Example
<?php $_variable = 200; $pyThon = 250; $Python = 300; $salary = 25.50; $total = $salary * $Python; $sayHello = "Hello World"; $say_hello = "Hello WOrld"; echo '$_variable=', $_variable, "<br/>"; echo '$pyThon=', $pyThon, "<br/>"; echo '$Python=', $Python, "<br/>"; echo '$sayHello=', $sayHello, "<br/>"; echo '$say_hello=', $say_hello, "<br/>"; echo '$salary=', $salary, "<br/>"; echo '$total=', $total, "<br/>"; echo '$_variable + $pyThon = ', ($_variable + $pyThon), "<br/>"; echo '$salary * $Python = ', ($salary * $Python), "<br/>"; ?>
Display Result
$_variable=200 $pyThon=250 $Python=300 $sayHello=Hello World $say_hello=Hello WOrld $salary=25.5 $total=7650 $_variable + $pyThon = 450 $salary * $Python = 7650
PHP Strings
- In PHP, we create a string with single, double quote, or heredoc.
- We use a blackslash (\) to escape single or double quote string.
Combine multiple string together by using period
- We use period . to concatenate two or many strings together.
Code (periodtest.php)
<?php $fname = "Bob"; $lname = "Maat"; $full_name = $fname . " " . $lname; echo "Name: " . $full_name . "<br/>"; # address $street_1 = "3232 Hilly Street"; $street_2 = "Savany Ave"; $city = "Houston"; $state = "Tx"; $zip = "77089"; $address = $street_1 . ", " . $street_2 . ", " . $city . " " . $state . " " . $zip; echo "Address: " . $address . "<br/>"; ?>
Display Result
Name: Bob Maat Address: 3232 Hilly Street, Savany Ave, Houston Tx 77089
String Example with single-quote
- We create string with a single-quote.
- A single quote is not escaped PHP variables.
<?php $fname = 'Bob'; $lname = 'Maat'; echo '$fname: '. $fname . '<br/>'; echo '$lname: '. $lname . '<br/>'; echo 'full name: ' echo $fname .' '. $lname. '<br/>'; ?>
Display Result
$fname: Bob $lname: Maat full name: Maat Bob
String example with double-quote
- We create a string with a double-quote.
- A single-quote does not support any special character, however a double quote string support many special character.
Code (doubleQuote.php)
<?php $fname = 'Bob'; $lname = 'Maat'; $fullname = $fname.' ' . $lname; echo "full name: \"$fullname\""; ?>
Display Result
full name: "Maat Bob"
Heredoc for multiple lines
- If we want to create a multiple line string, we can use the heredoc.
<?php $specialthing = 'Good day and good night'; $MyDOC = <<<THMYDOC Today is my special day <br/> I go out and visit some friends <br/> With you and me, we will have fun!<br/> $specialthing <br/> THMYDOC; echo $MyDOC; ?>
Display Result
Today is my special day I go out and visit some friends With you and me, we will have fun! Good day and good night
PHP Basic Array
- An array is a single variable, but it stores multiple values and its values can be integers or strings.
Code (myArray.php)
- Create an array and automatically assign it's index (index starts from 0)
<?php $fruit= array("apple","orange","graph","watermelon","banana"); ?>
Code (myArray2.php)
- Create an array and manually assign it's index
<?php $fruit[0] = "apple"; $fruit[1] = "orange"; $fruit[2] = "graph"; $fruit[3] = "watermelon"; $fruit[4] = "banana"; echo "I like to eat ". $fruit[4] . "<br/>"; echo "I also like to eat ". $fruit[3]. "<br/>"; ?>
Display Result
I like to eat banana I also like to eat watermelon
Associative Array
- An associated array contains KEY=>VALUE pair, and a key associates with a value.
- Create an associative array and automatically assign it's index.
Code (associArray.php)
<?php $student = array("bob"=>3.5, "janny"=>3.2, "yili"=>3.8, "utan" =>3.7, "john"=>3.2); ?>
Code (associArray2.php)
- An other alternative way to create an associative array.
<?php $student["bob"] = 3.5; $student["janny"] = 3.2; $student["yili"] = 3.8; $student["utan"] = 3.7; $student["john"] = 3.2; echo "Bob's GPA: ". $student["bob"] . "<br/>"; echo "Janny's GPA: ". $student["janny"] . "<br/>"; echo "Yili's GPA: ". $student["yili"] . "<br/>"; ?>
Display Result
Bob's GPA: 3.5 Janny's GPA: 3.2 Yili's GPA: 3.8
Display Array Structure with print_r() function
- print_r() function to display the array structure.
Code (printArray.php)
<?php $list = array("bob","birth","both","born"); print_r($list); ?>
Display Result
Array ( [0] => bob [1] => birth [2] => both [3] => born )
PHP Advanced Array
- The multiple arrays can be an associative array or just a normal array.
- Access multiple array is similar to access a single array, and we need to identify the array index.
Multiple Associative Array
<?php $multiple_arr = array( 'bob'=>array('gpa'=>3.7, 'semester'=>'fall 2011'), 'lili'=>array('gpa'=>3.5, 'semester'=>'fall 2010'), 'john'=>array('gpa'=>3.2,'semester'=>'fall 2009') ); echo $multiple_arr['bob']['gpa'] . "<br/>"; echo $multiple_arr['bob']['semester'] . "<br/>"; ?>
Display Result
3.7 fall 2011
Multiple Array Example
- We create three arrays, and we assign those arrays into another array.
<?php // student_id, first name, last name, date of birth, major $student_1 = array('CS23242','Janny','Lee','04/21/1985','Computer Science'); $student_2 = array('CS23444','John','Batz','02/25/1983','Computer Science'); $student_3 = array('CS23211','Marry','Zoe','01/03/1990','Computer Science'); $dept_computer = array($student_1, $student_2, $student_3); echo $dept_computer[0][0]. "<br/>"; echo $dept_computer[0][1]. "<br/>"; echo $dept_computer[0][2]. "<br/>"; echo $dept_computer[0][3]. "<br/>"; echo $dept_computer[0][4]. "<br/>"; ?>
Display Result
CS23242 Janny Lee 04/21/1985 Computer Science
PHP If statement
- If statement is a condition, and it states what need to be done.
- If you get up early, you need to do your homework.
- If you work hard, you will be rich.
- Usually, we use if statement to verify the condition.
- If something is happening, what needs to be done.
- The If statement checks a condition whether it is true or false.
If Statement
- Example: If it is rain, we are not go to school.
<?php // assign $rain equal one $rain=1; if( $rain == 1 ) { echo 'We are not go to school <br/>'; } else { echo 'We go to school. <br/>'; } ?>
Result
We are not go to school
If Statement 2
- If you work 40 hours, you get paid $40 per hour.
- If you work more than 40 hours, you get paid $60 per hour.
<?php $hour= 44; $total = 0; // this to check that the hour is assigned if($hour) { // when hour is 40 // when hour is less than 40 // when hour is greater than 0 if($hour == 40 && $hour < 40 && $hour > 0 ) { // total is equal the hour multiply by 40 $total = $hour * 40; } // this condition when the first condition is false // the hour is greater than 40 else { // to make sure the hour is larger than 40 if($hour > 40) { $total = ($hour-40) * 60 + 40*40; } } } // display the result echo 'You get paid:' . $total; ?>
Display Result
You get paid:1840
PHP If...Else
- 'If' and 'Else' statement uses to check whether the condition is true or false.
- When in the 'If' statement is true, the else condition will be ignored.
- However, when the If statement is false, it will go to the 'Else' statement.
Code (overTime.php)
- What is the result of this program?
<?php $overtime = 1 ; // set it to one make it always true $salary_hour = 17; // it is an hour salary rate $total_hour = 40; // total hour work per week $overtime_hour = 10; // overtime hour $total_salary = 0; // total salary if($overtime) { if($overtime_hour <= 10) { $total_salary = ($total_hour * $salary_hour) + ($overtime_hour * 25); echo "There is ". $overtime_hour . " hours of overtime<br/>"; echo "Total salary is ". $total_salary ; } else { $total_salary = ($total_hour * $salary_hour) + ($overtime_hour * 35); echo "There is ". $overtime_hour . " hours of overtime<br/>"; echo "Total salary is ". $total_salary ; } } else { $total_salary = $total_hour * $salary_hour; echo "There is no overtime work <br/>"; echo "Total salary is " . $total_salary . "<br/>"; } ?>
PHP If...Else If...Else
- The If statement uses for one condition,
- The If/Else uses for two conditions.
- The If/Elseif/Else uses for multiple conditions.
Code (ifElseIfElse1.php)
- If in the morning.
- We have breakfast and go to work.
- If it is not in the morning.
- We sleep at home.
<?php $day = 'morning'; if($day=='morning') { echo "Have breakfast and go to work. <br/>"; } else { echo "Sleep at home. <br/>"; } ?>
Result
Have breakfast and go to work.
Code (ifElseIfElse2.php)
- This example depends on the $day value.
- When the $day value is afternoon, it displays Good afternoon!.
- If the $day value is evening, it displays Good evening!.
<?php $day ='morning'; if($day=='morning') { echo "Good morning! <br/>"; } elseif($day=='afternoon') { echo "Good afternoon! <br/>"; } elseif($day=='evening') { echo "Good evening! <br/>"; } elseif($day =='night') { echo "Good night! <br/>"; } else { echo "Good day! <br/>"; } ?>
PHP Switch
- We can use switch statement to replace If/Elseif/Else condition statement.
- When the switch case statement matches the value of the switch expression, then it begins to executed the statements
- And, it will executes until it sees a break statement.
- Without a break statement, the case statement continues to match the switch expression until a case's statement list.
- Or, when it's finally reach the default statement.
- The switch statement is faster and clearer than the If/ElseIf/Else statement.
use If/Elseif/Else statement
Code (switch1.php)
<?php $input ='Day'; $package_charge = 0; if($input=='Day') { echo "You come here at day time <br/>"; $package_charge = 10; } elseif ($input=='Night') { echo "You come here at night time <br/>"; $package_charge = 5; } else { echo "Invalid input"; $package_charge = 0; } echo 'Package charge: '. $package_charge; ?>
Use switch statement
- The break keyword prevent the expression to continue for another case statement.
- Without the break keyword, the condition will continue and go on and on until it reaches a case's statement list.
Code (swithc2.php)
<?php $input ='Day'; $package_charge = 0; switch ($input) { case "Day": echo "You come here at day time <br/>"; $package_charge = 10; break; case "Night": echo "You come here at night time <br/>"; $package_charge = 5; break; default: echo "Invalid input"; $package_charge = 0; break; } echo 'Package charge: '. $package_charge; ?>
PHP While Loop
- The while loop uses to loop repeatedly through a condition.
- A condition could be true or false.
- According to the condition, it will execute the codes block.
Code (WhileExample.php)
- In this example, we check whether the $count is larger than 0.
- If the condition is true, it executes code block which is display the message.
- Within the code block, it reduces 1 from the $count value.
- It continues until the $count value is no longer larger than 0 or the condition is false.
<?php // display until the $count value is no longer larger than 0 $count = 4; while($count > 0) { echo "Count is ". $count . "<br/>"; $count--; } ?>
Display Result
Count is 4 Count is 3 Count is 2 Count is 1
Code(WhileExample2.php)
- In this example, the while loop remains true when the $count value is not equal to 25.
- The loop will stop when the $count value is equal to 25.
<?php // display until the $count is not equal 25; $count = 20; while($count != 25) { echo $count . "<br/>"; $count++; // add 1 to the $count for each loop } ?>
Display Result
20 21 22 23 24
Using While Loop to generate a Drop Down List
Code (while4dropdownlist.php)
- Here how we generate a HTML drop down list
<?php // list of a student array $student_name_list = array('Bob Maat','Johnny Zhar','Janny Tom','Tommy Kong','Kong Kam','Sopheap Som'); // count total students $total_student = count($student_name_list); echo "<select name=\"LIST\">"; while ($total_student > 0) { $total_student--; echo "<option value=\"". $total_student . "\">" . $student_name_list[$total_student] . "</option>"; } echo "</select>"; ?>
Result
<select name="LIST"> <option value="5">Sopheap Som</option> <option value="4">Kong Kam</option> <option value="3">Tommy Kong</option> <option value="2">Janny Tom</option> <option value="1">Johnny Zhar</option> <option value="0">Bob Maat</option> </select>
PHP Do While
Do While Vs. While
- The while requires a condition to be true (the truth condition is larger than 1 or not 0) in order for it to execute.
- However, for the do while, the do executes first and follow by the while.
Code (DoWhileExample.php)
- In this example, the echo function display the message first because the do statement executes first.
- In the while, the $count in decreasing by one till the condition returns false.
<?php $count = 4; do { echo "The count is ". $count . "<br/>"; }while($count--); ?>
Display Result
The count is 4 The count is 3 The count is 2 The count is 1 The count is 0
Code (WhileExample.php)
- In this example, the while return false because $total is not larger than 200. The echo function will not display.
<?php $total = 100; while ($total > 200) { echo "While display here first <br/>"; } ?>
Do While Example
- In this example, the echo function display the message "Will display here first" because the do executes first, and follow the while.
- It does not care whether the while returns true or false, because the do must execute first.
<?php $total = 100; do { echo "Will display here first <br/>"; }while($total > 200); ?>
Display Result
Will display here first
PHP For Loop
- The for loop contains the initialize value,
- Follow by the condition (check returns true or false, and check against the initialize value to a specific value),
- And, finally it increments or decrements the initialize value.
- And, a semicolon ";" needs to separate the expression.
Syntax
for(initialize value; condition; increment/decrement the initialize value) { code place here }
Code (htmlheader.php)
- Create HTML header with for loop: h1, h2, h3, h4, h5.
- In this for loop, we initialize the $i variable equal to 1, and check the condition with $i is less or equal to $list which is the number 5.
- The $i is increasing for every loop. In each loop, it echos out the html header.
<?php $list = 5; // This loop will generate the HTML header: h1, h2, h3, h4, h5 for($i = 1; $i <= $list; $i++) { echo "<h". $i . ">". "Hello". "</"."h".$i. ">"; } ?>
Display Result
<h1>Hello</h1><h2>Hello</h2><h3>Hello</h3><h4>Hello</h4><h5>Hello</h5>
For Loop Example with decrement
- In this example, we initialized the $i equal to $count which is 5, and in the condition we check for $i is larger than 0.
- Finally, we reduce or subtract 1 from the $i value in each loop.
Code (loopwithdecrement)
<?php $count = 5; for($i= $count; $i > 0; $i--) { echo $i . "<br/>"; } ?>
Display Result
5 4 3 2 1
Create HTML table with for loop
- In this example, we have an array with a list of number and we want to generate a table from that array.
- We used the count($score_list) to count the size of the array.
- And finally, we use the For loop to loop through the array to generate a table.
Code (htmltable.php)
<?php // list of the available score $score_list = array(21,52,12,42,52,11,42,55,21,32,13); echo "<table border=\"1\">"; echo "<tr><th>order</th><th>score</th></tr>"; for($fo=0; $fo< count($score_list); $fo++) { echo "<tr><td>". ($fo+1)."</td><td>" . $score_list[$fo] . "</td></tr>"; } echo "</table>"; ?>
Display Result
<table border="1"> <tr><th>order</th><th>score</th></tr> <tr><td>1</td><td>21</td></tr> <tr><td>2</td><td>52</td></tr> <tr><td>3</td><td>12</td></tr> <tr><td>4</td><td>42</td></tr> <tr><td>5</td><td>52</td></tr> <tr><td>6</td><td>11</td></tr> <tr><td>7</td><td>42</td></tr> <tr><td>8</td><td>55</td></tr> <tr><td>9</td><td>21</td></tr> <tr><td>10</td><td>32</td></tr> <tr><td>11</td><td>13</td></tr> </table>
Multiple Arrays with for loop
- In this example, we have multiple arrays,
- And, we combined three arrays into a single array.
- We have two for loops, the first for loop will loop through the main array,
- And, the second for loop will loop through the sub array.
<?php $score_1 = array(89,76,86,78,99,100); $score_2 = array(55,78,78,67,55,79); $score_3 = array(77,89,100,98,79,100); $score_list = array($score_1, $score_2, $score_3); for($i= 0; $i < count($score_list); $i++) { for($j=0; $j < count($score_list[$i]); $j++) { echo $score_list[$i][$j] . "<br/>"; } echo "-------<br/>"; } ?>
Display Result
89 76 86 78 99 100 ------- 55 78 78 67 55 79 ------- 77 89 100 98 79 100 -------
PHP For Each
- Use the foreach to iterate through an array or an associative array.
Foreach to loop through an array
- In this example, we have an array and we would like to iterate through that array elements.
- The array variable named $score contains a list of number, and we use the foreach
to loop through its element.
- In each loop, we assign the array element to the variable $s.
- The loop will be terminated until the foreach finished loop all the array elements.
<?php $score = array(23,43,23,54,52,32); foreach($score as $s) { echo $s . "<br/>"; } ?>
Display Result
23 43 23 54 52 32
Foreach to loop through an associative array
- This example loop through the associative array.
- The associative array is key and value pairs: key=>value
<?php $student_list = array ( 'Sopheap Chan'=>'Cambodia', 'Yiling Zheng'=>'China', 'Misumi Suo'=>'Japan', 'Johnny Lee'=>'South Korea' ); foreach($student_list as $key => $value) { echo $key . " is from ". $value. "<br/>"; } ?>
Display Result
Sopheap Chan is from Cambodia Yiling Zheng is from China Misumi Suo is from Japan Johnny Lee is from South Korea
PHP Function
- A function can be reused and its provide flexible for developer.
- In PHP, there are many built-in functions and these functions no need to be imported to the PHP program when use.
- However, if we write our own function, we need to import it to the program that are going to use it.
Example (functionExample.php)
- In this example, we have created two functions.
- The first function displays the title,
- And, the second function displays the body.
- The first function: show_title()
- The second function: show_body()
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Functions</title> </head> <body> <?php function show_title() { echo "<h3>Hello World</h3>"; } function show_body () { echo "<p>". "Good to hear that you have the great work to do." . "</p>"; } ?> <?php show_title(); ?> <div style="background-color:blue;"> I don't know you make the move to change it. However, <?php show_body(); ?> </div> </body> </html>
Display Result
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Functions</title> </head> <body> <h3>Hello World</h3> <div style="background-color:blue;"> I don't know you make the move to change it. However, <p>Good to hear that you have the great work to do</p> </div> </body> </html>
Function with parameter/argument
- The parameter is the valid PHP variable.
- The parameter passes to the function allow us more flexibility.
- Because, the parameter value can be used within the function block.
- A function can accept single or multiple parameters.
Syntax
<?php // function with single argument function my_function_name($arg) { } // function with multiple arguments function my_function_name2($arg, $arg2, $arg3) { } ?>
Code (functionwithpara.php)
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Functions With Parameters</title> </head> <body> <?php function show_title($title) { echo "<h3>$title</h3>"; } function show_body ($msg) { echo "<p>$msg</p>"; } ?> <?php show_title("Special Day"); ?> <div> <?php show_body("Today is a great day for both of you!"); ?> </div> </body> </html>
Display Result
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Functions With Parameters</title> </head> <body> <h3>Special Day</h3> <div> <p>Today is a great day for both of you!</p> </div> </body> </html>
PHP Form
- We can build user input form using PHP script or HTML script.
- And, the purpose of a form is to get user input.
Code (getName.html)
- This is a simple HTML page that it contains a simple form.
- And, this form contains one input box, and one submit button.
- When user type in his or her name, and click submit button.
- The form will send to the get_name.php file to process the user input.
- The getName.html HTML page is used to get the user input, and it will send to get_name.php for processing.
- We create this form use get method.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Form</title> </head> <body> <form action="get_name.php" method="get"> Name: <input type="text" name="student_name" size="20"/> <input type="submit" value="Submit"> </form> </body> </html>
Code (get_name.php)
- This PHP program has to place at the same directory with the getName.html HTML page.
- You need to type in the the name and click submit to send the HTML form data to the get_name.php for processing.
- $_GET['student_name'] is the get method for form submit.
<?php echo "Hello, ". $_GET['student_name'] . "<br/>"; ?>
Alternative form example
Code (studentForm.php)
- In tutorial, we create a student input form, and we write a custom function to generate a drop down list from arrays.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My PHP Form</title> </head> <body> <?php $school_list = array('MIT','YALE','LSU','UCLA','GSU','LATECH'); $major = array('Accounting','Banking','English','Political Science','Computer Science','Information Technology'); $school_type = array('full-time','part-time','remote'); function drop_down_list($arr, $name) { echo "<select name=\"$name\">"; foreach($arr as $vl) { echo "<option value=\"$vl\">". $vl . "</option>"; } echo "</select>"; } ?> <form action="process_form.php" method="get"> <table border="0"> <tr> <td colspan="2">Student Information</td> </tr> <tr> <td>Name:</td> <td><input type="text" name="FULLNAME" size="20"></td> </tr> <tr> <td>Age:</td> <td><input type="text" name="AGE" size="3"></td> </tr> <tr> <td>School:</td> <td><?php drop_down_list($school_list, 'SCHOOL'); ?></td> </tr> <tr> <td>Study:</td> <td><?php drop_down_list($major, 'MAJOR'); ?></td> </tr> <tr> <td>Type:</td> <td><?php drop_down_list($school_type, 'STUDENT_TYPE'); ?></td> </tr> <tr> <td colspan="2"><input type="submit"></td> </tr> </table> </form> </body> </html>
Code (process_form.php)
<?php $name = $_GET['FULLNAME']; $age = $_GET['AGE']; $school = $_GET['SCHOOL']; $major = $_GET['MAJOR']; $student_type = $_GET['STUDENT_TYPE']; echo "Your name is ". $name . "<br/>"; echo "You are " . $age . " year old <br/>"; echo "You studied at ". $school . "<br/>"; echo "You got your bachelor in ". $major . "<br/>"; echo "You was a ". $student_type . " student<br/>"; ?>
PHP POST
- $_POST uses to get a value from the post method.
- Generally, post method is more secured and it is used to process sensitive data.
- When the form uses the $_POST method, it will not display the user submit data to the URL.
Code(Login.html)
- This form requires two inputs: login email, and secure code.
- Thus, we use the post method to process the form data.
<html> <head> <title>Login</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="getLogin.php" method="post"> <table border="0"> <tr> <td>Login Email:</td> <td><input type="text" name="LoginEmail" size="20"></td> </tr> <tr> <td>Secure Code:</td> <td><input type="text" name="SecureCode" size="20"></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login"></td> </tr> </table> </form> </body> </html>
Code(getLogin.php)
- This is the PHP code for processing the HTML page.
Your email is: <?php echo $_POST["LoginEmail"]; ?> <br/> Secure Code is: <?php echo $_POST["SecureCode"]; ?> <br/>
PHP Process Form data using GET method
- $_GET["variable"]
- An associative array variable that passes through the get method from a form.
- The get method using form to pass a data through a URL.
Code (getPage.html) HTML page
- This is just a simple HTML page that allows a user to input name, id, and page.
- This form use get method.
<html> <head> <title>Test Get</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="process_getForm.php" method="get"> <table border="0"> <tr> <td colspan="2">Test GET</td> </tr> <tr> <td>Name:</td> <td><input type="text" name="fullname" size="20"></td> </tr> <tr> <td>ID:</td> <td><input type="text" name="id" size="3"></td> </tr> <tr> <td>Select Page :</td> <td> <select name="Page"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Fourth</option> <option value="5">Fifth</option> <option value="6">Six</option> </select> </td> </tr> <tr> <td colspan="2"><input type="submit" value="Check Out"></td> </tr> </table> </form> </body> </html>
Code (process_getForm.php)
- process_getForm.php?fullname=we&id=we&page=1
- We have to provide a user name, id, and page.
- When a user clicks on the "Check Out" button, the PHP program processes the form and display the user input.
<?php echo "Full Name: " . $_GET["fullname"] . "<br/>"; echo " Id: ". $_GET["id"] . "<br/>"; echo " Page: ". $_GET["page"] . "<br/>"; ?>
PHP Include
- In PHP the include(file name) takes a file name and file path, and it includes the file's content into another PHP page.
- The include(file name) is very useful when we want to include from another file.
- The most important part to remember is, we can create a file and use include() to include the file to every PHP pages.
- We can include text file, PHP file, or HTML page.
- We only need to modify the file that we've included from, and the modification will reflect to all the pages that included the file,
- Thus, we don't need to modify every page.
- The include() will display warning when it can not include the file.
- The include() and include_once() are the same, and the only different is include_once() will not be included again when the file is already included.
- The include_once() prevents the duplication function to be included twice.
Code (file1.php)
- This is the file1.php that we will include in the main.php file.
<?php echo "Hello world. <br/>"; echo "Good to hear. <br/>"; ?>
Code (main.php)
- We include the file1.php in this main.php file.
<?php include 'file_include.php'; echo "In this main file"; ?>
Display Result
Hello world. Good to hear. In this main file
This is the error message, you get when you failed to include a file
Warning when fail to include a file Warning: include(bodyw.php) [function.include]: failed to open stream: No such file or directory in /var/www/xprofile/include_home.php on line 3 Warning: include() [function.include]: Failed opening 'bodyw.php' for inclusion (include_path='.:/home/sophal/Smarty-2.6.26/libs/') in /var/www/xprofile/include_home.php on line 3 Copyright 2011 by our-group
PHP Require
- The require() is similar to include().
- The only different is that require() will generate an error when the file fails to include.
- And, it produces a fatal E_COMPILE_ERROR.
- The require_once() is similar to require().
- The difference is that the require_once() will include a file once only.
Code (addFunction.php)
- In this addFunction.php file contains two functions.
- We will use these two functions on the next PHP program to calculate and to generate a list of table.
<?php function add_number($number_aar) { $total = 0; for($i=0; $i <= count($number_aar); $i++) { $total += $number_aar[$i]; } return $total; } function generate_table ($array) { echo "<table border=\"1\">"; echo "<tr><td>#</td><td>Score</td><td>Total's Score</td></tr>"; for($i = 0; $i < count($array); $i++) { $total_ar += $array[$i]; echo "<tr><td>". ($i+1) . "</td><td>" . $array[$i] . "</td><td>" . $total_ar. "</td></tr>"; } echo "</table>"; } ?>
Code (testRequireOnce.php)
- We want to use add_number($number_aar) and generate_table($array) methods.
- The addFunction.php' file needs to be at the same directory of the testRequireOnce.php file.
- So, we need to import the add_opFunction.php file.
- We use the require_once() to import the file.
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Require Example</title> </head> <body> <?php // import an addFunction.php use require_once require_once 'addFunction.php'; $list_of_number = array(12,8,5,20,50); $total = add_number($list_of_number); echo "Total score is " . $total . "<br/>"; generate_table($list_of_number); ?> </body> </html>
Generate Result
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Require Example</title> </head> <body> <table border="1"> <tr><td>#</td><td>Score</td><td>Total's Score</td></tr> <tr><td>1</td><td>12</td><td>12</td></tr> <tr><td>2</td><td>8</td><td>20</td></tr> <tr><td>3</td><td>5</td><td>25</td></tr> <tr><td>4</td><td>20</td><td>45</td></tr> <tr><td>5</td><td>50</td><td>95</td></tr> </table> </body> </html>