PHP Tutorial_Saleh_4Q_Part (1)
PHP Tutorial_Saleh_4Q_Part (1)
• PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
• PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
Try it Yourself »
Exercise?
What does PHP stand for?
a) PHP: Hyperspeed Performance
b) PHP: Hyperformat Programming
c) PHP: Hypertext Preprocessor
d) PHP: Hyperlink Pages
Page 1 of 31
PHP Introduction
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor" [PHP originally stood for
"Personal Home Page"]
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
Page 2 of 31
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
Exercise?
What does PHP stand for?
a) PHP: Hyperspeed Performance
b) PHP: Hyperformat Programming
c) PHP: Hypertext Preprocessor
d) PHP: Hyperlink Pages
Page 3 of 31
PHP Installation
What Do I Need?
To start using PHP, you can:
• Find a web host with PHP and MySQL support
• Install a web server on your own PC, and then install PHP and MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php
Run »
<?php
$txt = "PHP";
echo "I love $txt!";
?>
I love PHP!
Try it Yourself »
PHP Version: To check your php version you can use the phpversion() function:
Example
Display the PHP version: echo phpversion();
Try it Yourself »
Page 4 of 31
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
An example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to
output the text "Hello World!" on a web page:
Example:
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Try it Yourself »
Page 5 of 31
PHP Case Sensitivity
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
In the following example, all three echo statements below are equal and legal:
Example
ECHO is the same as echo:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Try it Yourself »
• In the following example, only the first statement will display the value of the $color
variable!
• This is because $color, $COLOR, and $coLOR are treated as three different variables:
Example
$COLOR is not same as $color:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
Page 6 of 31
</body>
</html>
Try it Yourself »
Page 7 of 31
PHP Comments
• A comment in PHP code is a line that is not executed as a part of the program.
• Its only purpose is to be read by someone who is looking at the code.
/* This is a
multi-line comment */
Try it Yourself »
Page 8 of 31
• We can use comments to prevent code lines from being executed:
Exercise?
Which one is NOT a legal PHP comment:
a) # comment goes here
b) // comment goes here
c) '' comment goes here
d) /* comment goes here */
Page 9 of 31
Multi-line Comments
Try it Yourself »
Try it Yourself »
Try it Yourself »
Page 10 of 31
PHP Variables
Example: The variable $x will hold the value 5, and the variable $y will hold the value "John".
$x = 5;
$y = "John";
Try it Yourself »
• When you assign a text value to a variable, put quotes around the value.
• Unlike other programming languages, PHP has no command for declaring a variable.
• It is created the moment you first assign a value to it.
• Think of variables as containers for storing data.
PHP Variables
• A variable can have a short name (like $x and $y) or a more descriptive name ($age,
$carname, $total_volume).
Output Variables:
• The PHP echo statement is often used to output data to the screen.
Page 11 of 31
Try it Yourself »
Variable Types
• PHP has no command for declaring a variable, and the data type depends on the value
of the variable.
Example:
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
Try it Yourself »
Page 12 of 31
Example: To get the data type of a variable, use the var_dump() function.
$x = 5;
var_dump($x);
Try it Yourself »
Example:
$x = "John";
echo $x;
Try it Yourself »
Exercise?
Which one is NOT a legal PHP variable name:
a) $myVar = 3
b) $my_Var = 3
c) $myvar = 3
d) $my-var = 3
Page 13 of 31
PHP Variables Scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
Page 14 of 31
PHP The global Keyword:
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function).
Example:
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
Try it Yourself »
Example:
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
Try it Yourself »
Page 15 of 31
• Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
• Note: The variable is still local to the function.
Example:
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
Try it Yourself »
Exercise?
Consider the following code:
$name = 'Linus';
function myTest() {
$name = 'Tobias';
}
myTest();
echo $name;
What will be the output?
a) Linus
b) Tobias
// If you wanted the function to modify the global $name, you would need to explicitly declare it
as global inside the function:
$name = 'Linus';
function myTest() {
global $name;
$name = 'Tobias';
}
myTest();
echo $name; // Outputs: Tobias
Page 16 of 31
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print.
Example:
echo "Hello";
//same as:
echo("Hello");
Try it Yourself »
Display Text
• To output text, use the echo command (the text can contain HTML markup):
Example:
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
Try it Yourself »
Display Variables
• To output text and variables use the echo statement:
Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
echo "<h2>$txt1</h2>";
echo "<p>Study PHP at $txt2</p>";
Try it Yourself »
Page 17 of 31
Using Single Quotes:
• Strings are surrounded by quotes, but there is a difference between single and double
quotes in PHP.
• When using double quotes, variables can be inserted to the string as in the example
above.
• When using single quotes, variables have to be inserted using the . operator.
Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
Example:
print "Hello";
//same as:
print("Hello");
Try it Yourself »
Display Text
• To output text, use the print command (the text can contain HTML markup):
Example:
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
Try it Yourself »
Display Variables
• To output text and variables with the print statement:
Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
Page 18 of 31
print "<h2>$txt1</h2>";
print "<p>Study PHP at $txt2</p>";
Try it Yourself »
Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
Exercise?
The two echo statements below will produce the same result:
$name = 'Linus';
echo '<h1>Hello $name</h1>';
echo "<h1>Hello $name</h1>";
a) True
b) False
$name = 'Linus';
echo '<h1>Hello $name</h1>'; // Outputs: <h1>Hello $name</h1>
echo "<h1>Hello $name</h1>"; // Outputs: <h1>Hello Linus</h1>
$name = 'Linus';
echo '<h1>Hello ‘ . $name . ‘</h1>'; // Outputs: <h1>Hello Linus </h1>
echo "<h1>Hello $name</h1>"; // Outputs: <h1>Hello Linus</h1>
Page 19 of 31
PHP Data Types
Example: The var_dump() function returns the data type and the value.
$x = 5;
var_dump($x);
Try it Yourself »
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes.
Example:
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
Try it Yourself »
PHP Integer
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Page 20 of 31
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation
Example: $x is an integer. The PHP var_dump() function returns the data type and value:
$x = 5985;
var_dump($x);
Try it Yourself »
PHP Float
• A float (floating point number) is a number with a decimal point or a number in
exponential form.
Example: $x is a float. The PHP var_dump() function returns the data type and value:
$x = 10.365;
var_dump($x);
Try it Yourself »
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.
Example:
$x = true;
var_dump($x);
Try it Yourself »
PHP Array
• An array stores multiple values in one single variable.
Example: In the following example $cars is an array. The PHP var_dump() function returns
the data type and value:
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
Try it Yourself »
Page 21 of 31
PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
Let's assume we have a class named Car that can have properties like model, color, etc.
• We can define variables like $model, $color, and so on, to hold the values of these
properties.
• When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
• If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.
Example:
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
Page 22 of 31
Example:
$x = "Hello world!";
$x = null;
var_dump($x);
Try it Yourself »
Example:
$x = 5;
var_dump($x);
$x = "Hello";
var_dump($x);
Try it Yourself »
Example: Casting
$x = 5;
$x = (string) $x;
var_dump($x);
Try it Yourself »
PHP Resource:
• The special resource type is not an actual data type.
• It is the storing of a reference to functions and resources external to PHP.
• A common example of using the resource data type is a database call.
Exercise?
What data type is the $x variable below:
$x = true;
a) Integer
b) Boolean
c) Float
d) String
Page 23 of 31
PHP Strings
Strings
• Strings in PHP are surrounded by either double quotation marks, or single quotation
marks.
• There is a big difference between double quotes and single quotes in PHP.
Double quotes process special characters, single quotes does not.
Example:
echo "Hello";
echo 'Hello';
Try it Yourself »
Example: Double quoted string literals perform operations for special characters:
$x = "John";
echo "Hello $x";
Try it Yourself »
String Length
• The PHP strlen() function returns the length of a string.
Page 24 of 31
Word Count
• The PHP str_word_count() function counts the number of words in a string.
Example: Search for the text "world" in the string "Hello world!":
echo strpos("Hello world!", "world");
Try it Yourself »
Exercise?
What will be the output of the following code:
$x = 5;
echo 'The price is $x';
a) The price is 5
b) The price is
c) The price is $x
• If you wanted the variable $x to be parsed and included in the string, you would use
double quotes:
echo "The price is $x"; // Output: The price is 5
Page 25 of 31
PHP - Modify Strings
PHP has a set of built-in functions that you can use to modify strings.
Upper Case
Example: The strtoupper() function returns the string in upper case:
$x = "Hello World!";
echo strtoupper($x);
Try it Yourself »
Lower Case
Example: The strtolower() function returns the string in lower case:
$x = "Hello World!";
echo strtolower($x);
Try it Yourself »
Replace String
• The PHP str_replace() function replaces some characters with some other characters in a
string.
Reverse a String
• The PHP strrev() function reverses a string.
Example: Reverse the string "Hello World!":
$x = "Hello World!";
echo strrev($x);
Try it Yourself »
Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
Example: The trim() removes any whitespace from the beginning or the end:
$x = " Hello World! ";
echo trim($x);
Try it Yourself »
Page 26 of 31
Convert String into Array
• The PHP explode() function splits a string into an array.
• The first parameter of the explode() function represents the "separator".
• The "separator" specifies where to split the string.
• The separator is required.
Example: Split the string into an array. Use the space character as separator:
$x = "Hello World!";
$y = explode(" ", $x);
/*
Result:
Array ( [0] => Hello [1] => World! )
*/
Try it Yourself »
Exercise?
What is the correct function to return a string as all upper case letters:
a) touppercase()
b) strtoupper()
c) ucase()
d) toupper()
Page 27 of 31
PHP - Concatenate Strings
String Concatenation
• To concatenate, or combine, two strings you can use the . operator:
Example:
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
// The result is HelloWorld, without a space between the two words.
Try it Yourself »
Example: You can add a space character like this:
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
Try it Yourself »
• An easier and better way is by using the power of double quotes.
• By surrounding the two variables in double quotes with a white space between them, the
white space will also be present in the result.
Example
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
Try it Yourself »
Exercise?
What will be the result of $z in the following code example:
$x = 5;
$y = 10;
$z = "$x . $y";
echo $z;
a) 5 . 10
b) 15
c) 5.10
• If you wanted to concatenate $x and $y properly, you would need to use the . operator
outside the string: $z = $x . $y; // $z will be "510"
• Or concatenate explicitly inside the string: $z = "$x" . "$y"; // $z will be "510"
Page 28 of 31
PHP - Slicing Strings
Slicing
• You can return a range of characters by using the substr() function.
• Specify the start index and the number of characters you want to return.
• The first character has index 0.
Example: Start the slice at index 6 and end the slice 5 positions later:
$x = "Hello World!";
echo substr($x, 6, 5);
Try it Yourself »
Example: Start the slice at index 6 and go all the way to the end:
$x = "Hello World!";
echo substr($x, 6);
Try it Yourself »
Example: Get the 3 characters, starting from the "o" in world (index -5):
$x = "Hello World!";
echo substr($x, -5, 3);
Try it Yourself »
Negative Length
• Use negative length to specify how many characters to omit, starting from the end of
the string:
Example:
• From the string "Hi, how are you?", get the characters starting from index 5, and continue
until you reach the 3. character from the end (index -3).
• Should end up with "ow are y":
$x = "Hi, how are you?";
echo substr($x, 5, -3);
Try it Yourself »
Page 29 of 31
Exercise?
What will be the result of the following slice:
$x = "Hello World!";
echo substr($x, 3, 2);
a) ll
b) el
c) lo
Page 30 of 31
PHP - Escape Characters
Escape Character
• To insert characters that are illegal in a string, use an escape character.
Example:
$x = "We are the so-called "Vikings" from the north."; \\ PHP Parse Error
Try it Yourself »
\t Tab Try it »
\f Form Feed
Page 31 of 31