Unit 4
Unit 4
PHP Variables
Variables are "containers" for storing information. A variable can have a short name (like $x and $y) or
a more descriptive name ($age, $carname, $total_volume).
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• 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 alpha-numeric characters 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.
The following example will show how to output text and a variable:
Example
$txt = "W3Schools.com";
echo "I love $txt!";
Example
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the variable.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
Get the Type
To get the data type of a variable, use the var_dump() function.
Example
The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x);
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
$x = "John";
echo $x;
Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:
Example
Variable with global scope:
$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();
Local Scope
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
Example
Variable with local scope:
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
myTest();
myTest();
myTest();
PHP Constants
Constants are like variables, except that once they are defined they cannot be changed or undefined.
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).
Note: Unlike variables, constants are automatically global across the entire script.
To create a constant, use the define() function.
Syntax
define(name, value);
Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
Example
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
Constants are Global: Constants are automatically global and can be used across the entire script.
PHP Operators
Operators are used to perform operations on variables and values.
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
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
x=y x=y The left operand gets set to the value of the Try it »
expression on the right
x %= y x=x%y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
<= Less than or equal to $x <= $y Returns true if $x is less than Try it »
or equal to $y
PHP has two operators that are specially designed for strings.
PHP Loops
Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script, we
can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true.
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
OUTPUT: 12
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;
</body>
</html>
OUTPUT: 1245
Example
Count to 100 by tens:
$i = 0;
while ($i < 100) {
$i+=10;
echo $i "<br>";
}
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
The PHP for Loop
The for loop is used when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) {
// code block
}
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iteration
• expression3 is evaluated after each iteration
Example
Print the numbers from 0 to 10:
What is an Array?
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.
Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
You can have different data types in the same array.
Example
Array items of four different data types:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);
Indexed Arrays: These arrays use numeric indices. You can create an indexed array like
this:
$fruits = array("Apple", "Banana", "Cherry");
Associative Arrays: These arrays use named keys that you assign to them. They are
useful when you want to associate values with specific keys.
$ages = array("Alice" => 25, "Bob" => 30, "Charlie" => 35);
Multidimensional Arrays: These are arrays that contain one or more arrays. You can
think of them as arrays of arrays. They are often used to store data in a tabular format.
$contacts = array(
"John" => array("phone" => "123-4567", "email" => "[email protected]"),
"Jane" => array("phone" => "987-6543", "email" => "[email protected]")
);
STRING
A string is a sequence of characters, Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.
Example
echo "Hello";
echo 'Hello';
String Length
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
Word Count
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
1. Upper Case
Example
The strtoupper() function returns the string in upper case:
$x = "Hello World!";
echo strtoupper($x);
2. Lower Case
Example
The strtolower() function returns the string in lower case:
$x = "Hello World!";
echo strtolower($x);
3. Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello World!":
$x = "Hello World!";
echo strrev($x);
4. String Concatenation
To concatenate, or combine, two strings you can use the . operator:
Example
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
You can add a space character like this:
Example
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
PHP Environment
A PHP environment refers to the software setup required for running PHP scripts. It typically
includes:
1. Web Server (e.g., Apache, Nginx) – to handle requests and serve PHP scripts.
2. PHP Interpreter – to execute PHP code.
3. Database (optional, e.g., MySQL, PostgreSQL) – if the PHP scripts require database
interaction.
The environment ensures that PHP scripts are processed and the output (e.g., HTML) is sent to the
user’s browser.
Components of a PHP Environment:
• Operating System (OS): Linux, Windows, macOS.
• Web Server: Serves the PHP script to the client (e.g., Apache or Nginx).
• PHP Engine: The interpreter that parses and runs PHP code.
• Database: Optional, for storing and retrieving data (e.g., MySQL, MariaDB).
• Development Tools: Tools like PHPStorm or Xdebug for debugging and development.
Popular PHP Environment Stacks:
• LAMP Stack (Linux, Apache, MySQL, PHP): A common setup for running PHP
applications on Linux.
• XAMPP/WAMP (Windows): For local development on Windows.
• MAMP (Mac): For local development on macOS.
echo json_encode($data);
?>
• header('Content-Type: application/json'): Sets the Content-Type header to application/json,
indicating the response is JSON.
• json_encode(): Converts an array or object to JSON format.
HTTP Status Codes in PHP
PHP allows you to send custom HTTP status codes along with responses. For example:
<?php
http_response_code(404);
echo "Page not found!";
?>
• http_response_code(): Sets the HTTP status code (e.g., 404 for Not Found, 200 for OK).
PHP Files
In PHP, file handling is a fundamental aspect that allows you to create, open, read, write, and manage
files on the server. This capability is crucial for many web applications, such as storing logs, user
uploads, or generating dynamic content. Below is an overview of key file operations in PHP, along
with commonly used functions and examples.
1. Basic File Handling Functions
File Opening and Closing:
• fopen($filename, $mode): Opens a file in a specified mode. Returns a file pointer resource
on success or false on failure.
• fclose($filePointer): Closes an open file pointer.
File Modes:
• "r": Read-only. Starts at the beginning of the file.
• "r+": Read/Write. Starts at the beginning of the file.
• "w": Write-only. Truncates the file to zero length or creates a new file if it doesn't exist.
• "w+": Read/Write. Truncates the file to zero length or creates a new file.
• "a": Write-only. Starts at the end of the file or creates a new file.
• "a+": Read/Write. Starts at the end of the file.
• "x": Write-only. Creates a new file. Returns false if the file exists.
• "x+": Read/Write. Creates a new file. Returns false if the file exists
Cookies in PHP
Cookies are small pieces of data stored on the client’s browser, which can be used to remember
information about the user across different pages or sessions.
Setting a Cookie
To set a cookie in PHP, use the setcookie() function:
setcookie("username", "JohnDoe", time() + (86400 * 30), "/");
// Parameters: (name, value, expiry_time, path)
• name: The name of the cookie.
• value: The value of the cookie.
• expiry_time: The expiration time (in seconds). time() + (86400 * 30) sets the cookie to
expire in 30 days.
• path: The path on the server in which the cookie will be available.
Retrieving a Cookie
To retrieve a cookie, use the $_COOKIE superglobal array:
if(isset($_COOKIE["username"])) {
echo "Username is: " . $_COOKIE["username"];
} else {
echo "Cookie is not set.";
}
Deleting a Cookie
To delete a cookie, set its expiration time to a past date:
setcookie("username", "", time() - 3600, "/");
Sessions in PHP
Sessions are a way to store information across multiple pages of a website, but unlike cookies, the
data is stored on the server. PHP assigns a unique session ID to the client, which is then used to access
the stored data on the server.
Starting a Session
To start a session, use the session_start() function. It should be called at the beginning of the script
before any output is sent to the browser.
session_start();
Storing and Retrieving Session Variables
Session variables are stored in the $_SESSION superglobal array.
// Storing session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";