PHP
What is PHP?
PHP (Hypertext Preprocessor) is a widely-used, open-source programming language especially suited for web development.
It’s a
server-side scripting language, which means
the code runs on the web server rather than on the user’s browser.
- ★ PHP is an acronym for "PHP: Hypertext Preprocessor".
- ★ PHP is a
server scripting language
, and a powerful tool for making dynamic and interactive Web pages.
- ★ PHP is a widely-used, open source scripting language.
- ★ PHP scripts are
executed on the server
.
- ★ PHP is free to download and use
- ★ PHP 8 is the latest stable release.
What is a PHP File?
- ★ PHP files can contain text, HTML, CSS, JavaScript, and PHP code
- ★ PHP code is executed on the server, and the result is returned to the browser as plain HTML
- ★ PHP files have extension "
.php
"
What Can PHP Do?
- ★ PHP can generate dynamic page content.
- ★ PHP can create, open, read, write, delete, and close files on the server.
- ★ PHP can collect form data.
- ★ PHP can send and receive cookies.
- ★ PHP can add, delete, modify data in your database.
- ★ PHP can be used to control user-access.
- ★ PHP can encrypt data.
Key Features of PHP:
- Dynamic Content:PHP is often used to generate dynamic page content.
For example, it can pull data from a database and display it on a website in real-time.
- Integration with HTML and CSS: PHP code can be embedded directly into HTML,
making it easy to create dynamic pages without having to separate the code from the design.
- Database Interaction: PHP works well with various database systems (such as MySQL, PostgreSQL, and others),
making it a strong choice for creating data-driven websites.
- Ease of Use: PHP is known for its relatively simple syntax and a wide range of built-in functions,
making it accessible to beginners while still powerful enough for advanced users.
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.
- ★ 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.
Basic PHP Syntax
- ★ A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
- ★ A PHP script can be placed anywhere in the document.
- ★ A PHP script starts with
<?php
and ends with
?>
- ★ PHP statements end with a semicolon (
;
)
- ★ A PHP file normally contains HTML tags, and some PHP scripting code.
- ★ Below, we have 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:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello!";
?>
</body>
</html>
PHP Case Sensitivity
- ★ Keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are not case-sensitive.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
However, tt’s generally a good practice to stick to a consistent naming style (like always using lowercase) for readability.
★ All variable names are case-sensitive!
<!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>";
?>
</body>
</html>
Comments
<?php
// This is a single-line comment
# This is also a single-line comment
?>
★ Multi-line comments
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
PHP Variables
Creating (Declaring) PHP Variables
- ★ In PHP, a variable starts with the
$
sign, followed by the name of the variable.
- ★ Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created
the moment you first assign a value to it.
- ★ You can use the gettype() function to identify the type of a variable.
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
$flag = True;
echo gettype($txt);
echo "<br>";
echo gettype($x);
echo "<br>";
echo gettype($y);
echo "<br>";
echo gettype($flag);
?>
Rules for PHP variables
- ★ A variable name must start with a letter or the underscore character
- ★ A variable name cannot start with a number
- ★ A variable name can only contain letters, numbers, and underscores (A-z, 0-9, and _ )
- ★ Variable names are case-sensitive ($age and $AGE are two different variables)
Output Variables
- ★ The PHP echo statement is often used to output data to the screen.
<?php
$txt = "MTSU";
echo "I love $txt!";
?>
<?php
$txt = "MTSU";
echo "I love " . $txt . "!";
?>
The
dot operator (.) is used to
concatenate strings or variables together in PHP.
PHP Variables Scope
PHP has three different variable scopes:
- ★ local
- ★ global
- ★ static
1. Local
- ♣ A variable declared
within a function
has a LOCAL SCOPE and can only be accessed within that function.
- ♣ It cannot be accessed outside of that function.
//Example:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
//Using x outside the function will cause an error: Undefined variable
echo "<p>Variable x outside function is: $x</p>";
?>
2. Global
- ♣ A variable declared
outside any function or class
has a GLOBAL SCOPE.
- ♣ It can be accessed anywhere outside functions or classes, but not directly inside them.
- ♣ Using the variable x inside the function will cause an error: Undefined variable
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
Using global Keyword Inside Functions:
- ★ 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):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Using $GLOBALS Inside Functions:
- ★ PHP also stores all global variables in an array called
$GLOBALS[index]
. The index holds the name of
the variable.
- ★ Even if a variable is not declared as global within a function, you can still access it using $GLOBALS.
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
3. Static
A static variable inside a function retains its value across multiple calls.
Normally, a local variable is reset each time the function is called. By declaring it static, the variable keeps its previous value.
- ★ Normally, when a function is completed/executed, all of its variables are deleted.
- ★ sometimes we want a local variable
NOT
to be deleted by using the static keyword.
- ★ To do this, use the
static
keyword when you first declare the variable.
- ★ 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.
<?php
function myCounter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
myCounter(); //Outputs 1
myCounter(); //Outputs 2
myCounter(); //Outputs 3
?>
PHP echo and print Statements
- ★ With PHP, there are two basic ways to get output:
echo
and
print
.
- ★ They are both used to output data to the screen.
- ★ echo has no return value.
- ★ print has a return value of 1
- ★ echo can take multiple parameters (although such usage is rare) while print can take one argument.
- ★ The echo statement can be used with or without parentheses:
echo
or
echo()
.
- ★ The print statement can be used with or without parentheses:
print
or
print()
.
- ★ Notice that the text can contain HTML markup
- ★ echo is generally preferred for simple output tasks due to its speed and flexibility.
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y . "<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
PHP Data Types
PHP supports the following data types:
- ★
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:
$x = "Hello world!";
var_dump($x);
echo "<br>";
$y = 'Hello world!';
var_dump($y);
Note: var_dump() function returns the data type and value;
☆ Single and double quotes generally behave the same for simple strings, but double quotes allow variable interpolation and certain escape sequences:
- 1. Variable Interpolation
- ♣ If you place a variable inside a double-quoted string, PHP will automatically replace it with the variable’s value.
- ♣ No need to concatenate the variable; it’s interpreted directly within the string.
$name = "Alice";
echo "Hello, $name! <br>"; // Outputs: Hello, Alice!
echo 'Hello, $name!'; // Outputs: Hello, $name! (literal $name, no interpolation)
2. Escape Sequences
- ♣ Within double quotes, you can use certain escape sequences to represent special characters.
echo "She said, \"Hello!\" <br>"; // Outputs: She said, "Hello!"
echo 'She said, \"Hello!\"'; // Outputs: She said, \"Hello!\"
★
Integer
- ☆ An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647 on a 32-bit system.
$x = 100;
var_dump($x);
★
Float
(floating point numbers - also called double)
- ☆ A float (floating point number) is a number with a decimal point or a number in exponential form.
<?php
$x = 10.365;
var_dump($x);
?>
★
Boolean
- ☆ A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
★
Array
- ☆ An array stores multiple values in one single variable.
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
★
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.
- ☆ An object is a data type which stores data and information on how to process that data.
- ☆ If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.
- ☆ In PHP, an object must be explicitly declared.
- ☆ Notice that the construct function starts with two underscores (__)!
<?php
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 . "!";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
★
NULL
- ☆ Null is a special data type which can have only one value: NULL.
- ☆ A variable of data type NULL is a variable that has no value assigned to it
- ☆ If a variable is created without a value, it is automatically assigned a value of NULL.
- ☆ Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
if (is_null($x)) {
echo "The variable is NULL";
}
?>
★
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.
- ☆ Common Examples of Resources:
- ♣ File Handles:
A reference to an open file, returned by fopen().
- ♣ Database Connections:
A connection to a database server, returned by functions like mysqli_connect()
PHP String Function
- ★
strlen()
: Return the Length of a String
<?php
echo strlen("Hello world!"); // outputs 12
?>
★
str_word_count()
: Count the Number of Words in a String
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
★
strrev()
: Reverse a String
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Here’s a simple PHP program that uses
strrev() to check if a given string is a palindrome
(a word, phrase, or sequence that reads the same backward as forward):
function isPalindrome($string) {
// Remove whitespace and convert the string to lowercase for uniformity
$normalizedString = strtolower(str_replace(' ', '', $string));
// Reverse the normalized string
$reversedString = strrev($normalizedString);
// Check if the original normalized string matches the reversed string
return $normalizedString === $reversedString;
}
// Test the function
$inputString = "radar";
if (isPalindrome($inputString)) {
echo "$inputString is a palindrome.";
} else {
echo "$inputString is not a palindrome.";
}
★
strpos()
: Search For a Text Within a String
- ★ The PHP strpos() function searches for a specific text within a string.
- ★ If a match is found, the function returns the character position of the first match.
- ★ If no match is found, it will return FALSE.
- ★ The first character position in a string is 0
<?php
echo strpos("Hello world!", "world"); // outputs 6, 6 is the start index of "world", 0 is the first index in PHP
?>
★
str_replace()
: Replace Text Within a String
- ☆ The PHP str_replace() function replaces some characters with some other characters in a string.
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
echo str_replace("World", "Dolly", "Hello world!"); // outputs Hello world!
?>
PHP Numbers
PHP Integers
PHP has the following functions to check if the type of a variable is integer:
- ★ is_int()
- ★ is_integer(): alias of is_int()
- ★ is_long(): alias of is_int()
<?php
$x = 5985;
var_dump(is_int($x));
$x = 59.85;
var_dump(is_int($x));
?>
PHP Floats
PHP has the following functions to check if the type of a variable is float:
- ★ is_float()
- ★ is_double(): alias of is_float()
PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
PHP has the following functions to check if a numeric value is finite or infinite:
- ★ is_finite()
- ★ is_infinite()
<?php
$x = 1.9e411;
var_dump($x);
echo "<br>";
var_dump(is_infinite($x));
?>
PHP NaN
NaN stands for Not a Number.
PHP has the following functions to check if a value is not a number:
<?php
$x = acos(8);
var_dump(is_nan($x));
?>
PHP Numerical Strings
- ★ The PHP is_numeric() function can be used to find whether a variable is numeric.
- ★ The function returns true if the variable is a number or a numeric string, false otherwise.
<?php
$x = 5985;
var_dump(is_numeric($x));
$x = "5985";
var_dump(is_numeric($x));
$x = "59.85" + 100;
var_dump(is_numeric($x));
$x = "Hello";
var_dump(is_numeric($x));
?>
PHP Constants
- ★ A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
- ★ A valid constant name starts with a letter or underscore (no $ sign before the constant name).
- ★ Unlike variables, constants are automatically global across the entire script.
- ★ To create a constant, use the
define()
function.
Syntax: define(name, value)
- ★ const keyword (introduced in PHP 5.3):
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING; //constants are referenced without a $
const SITE_URL = "https://www.example.com";
echo SITE_NAME;
?>
PHP Constant Arrays
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
Note:
Constants are automatically
global
and can be used across the entire script.
PHP Operators
PHP divides the operators in the following groups:
- ★ Arithmetic operators
- ★ Assignment operators
- ★ Comparison operators
- ★ Increment/Decrement operators
- ★ Logical operators
- ★ String operators
- ★ Array operators
- ★ Conditional assignment operators
PHP Arithmetic Operators
Operator |
Name |
Example |
+ |
Addition |
$x + $y |
- |
Subtraction |
$x - $y |
* |
Multiplication |
$x * $y |
/ |
Division |
$x / $y |
% |
Module |
$x % $y |
** |
Exponentiation |
$x ** $y |
PHP Assignment Operators
Assignment |
same as |
x = y |
x = y |
x += y |
x = x+ y |
x -= y |
x = x - y |
x *= y |
x = x*y |
x /= y |
x = x/y |
x %= y |
x = x%y |
PHP Comparison Operators
Operator |
Name |
Example |
Result |
== |
Equal |
$x == $y |
Returns true if $x is equal to $y |
=== |
Identical |
$x === $y |
Returns true if $x is equal to $y, and they are of the same type |
!= |
Not Equal |
$x != $y |
Returns true if $x is not equal to $y |
<>
|
Not equal |
$x <> $y |
Returns true if $x is not equal to $y |
!== |
Not Identical |
$x !== $y |
Returns true if $x is not equal to $y, or they are not of the same type |
> |
Greater than |
$x > $y |
Returns true if $x is greater than $y |
> |
Less than |
$x < $y |
Returns true if $x is less than $y |
>= |
Greater than or equal to |
$x >= $y |
Returns true if $x is greater than or equal to $y |
<= |
Less than or equal to |
$x <= $y |
Returns true if $x is less than or equal to $y |
<=>
|
Spaceship |
$x <=> $y |
Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or
greater than $y. Introduced in PHP 7. |
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
echo ($x <=> $y); // returns -1 because $x is less than $y
echo "<br>";
$x = 10;
$y = 10;
echo ($x <=> $y); // returns 0 because values are equal
echo "<br>";
$x = 15;
$y = 10;
echo ($x <=> $y); // returns +1 because $x is greater than $y
?>
</body>
</html>
Common Use Cases: Sorting
Example 1: Sorting an array of numbers using an arrow function
$arr = [3, 1, 4, 2];
// Print each item before sorting
echo "Before sorting: <br>";
foreach ($arr as $item) {
echo $item . "<br>";
}
// Sort the array using usort and a lambda function
// usort() stands for "user-defined sort".
usort($arr, fn($a, $b) => $a <=> $b); //This sorts the array $arr in ascending order
// Print each item after sorting
echo "After sorting: <br>";
foreach ($arr as $item) {
echo $item . "<br>";
}
Example 2: Sorting an array of objects using an arrow function
// Define a simple class
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
}
// Create an array of Product objects
$products = [
new Product("Apple", 2.50),
new Product("Banana", 1.20),
new Product("Cherry", 3.578),
new Product("Date", 2.00)
];
// Sort by price (ascending) using an arrow function
usort($products, fn($a, $b) => $a->price <=> $b->price);
// Display sorted products
echo "Sorted by price (ascending):<br>";
foreach ($products as $product) {
echo $product->name . " - $" . number_format($product->price, 2) . "<br>";
}
To sort by name instead, simply change the comparator:
usort($products, fn($a, $b) => strcmp($a->name, $b->name));
Sorting by multiple criteria
// Sort by price, then by name
usort($products, fn($a, $b) =>
$a->price <=> $b->price ?: strcmp($a->name, $b->name)
);
PHP Increment / Decrement Operators
Operator |
Name |
Description |
++$x |
Pre-increment |
Increments $x by one, then returns $x |
$x++ |
Post-increment |
Returns $x, then increments $x by one |
--$x |
Pre-decrement |
Decrements $x by one, then returns $x |
$x-- |
Post-decrement |
Returns $x, then decrements $x by one |
PHP Logical Operators
Operator |
Name |
Example |
Result |
and |
And |
$x and $y |
True if both $x and $y are true |
or |
Or |
$x or $y |
True if either $x or $y is true |
xor |
Xor |
$x xor $y |
True if either $x or $y is true, but not both |
&& |
And |
$x && $y |
True if both $x and $y are true |
|| |
Or |
$x || $y |
True if either $x or $y is true |
! |
Not |
!$x |
True if $x is not true |
PHP String Operators
Operator |
Name |
Example |
Result |
. |
Concatenation |
$txt1 . $txt2 |
Concatenation of $txt1 and $txt2 |
.= |
Concatenation assignment |
$txt1 .= $txt2 |
Appends $txt2 to $txt1 |
PHP Array Operators
Operator |
Name |
Example |
Result |
+ |
Union |
$x + $y |
Union of $x and $y |
== |
Equality |
$x == $y |
Returns true if $x and $y have the same key/value pairs |
=== |
Identity |
$x === $y |
Returns true if $x and $y have the same key/value pairs in the same order and of the same types |
!= |
Inequality |
$x != $y |
Returns true if $x is not equal to $y |
<>
|
Inequality |
$x <> $y |
Returns true if $x is not equal to $y |
!== |
Non-identity |
$x !== $y |
Returns true if $x is not identical to $y |
Reference
www.w3schools.com