PHP Tutorial

PHP Tutorial

PHP Introduction

PHP code is executed on the server.


What You Should Already Know

Before you continue you should have a basic understanding of the following:

If you want to study these subjects first, find the tutorials on our Home page.


What is PHP?

  • PHP is an acronym for “PHP: Hypertext Preprocessor”
  • PHP is a widely-used, open-source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
It is deep enough to run large social networks!
It is also easy enough to be a beginner’s first server-side language!


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 the extension “.php

What Can PHP Do?

  • PHP can generate the 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, and modify data in your database
  • PHP can be used to control user-access
  • PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF files. You can also output any text, such as XHTML and XML.



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

What’s new in PHP 7

  • PHP 7 is much faster than the previous popular stable release (PHP 5.6)
  • PHP 7 has improved Error Handling
  • PHP 7 supports stricter Type Declarations for function arguments
  • PHP 7 supports new operators (like the spaceship operator: <=>)

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

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.

Just create some .php files, place them in your web directory, and the server will automatically parse them for you.

You do not need to compile anything or install any extra tools.

Because PHP is free, most web hosts offer PHP support.


Set Up PHP on Your Own PC

However, if your server does not support PHP, you must:

  • install a web server
  • install PHP
  • install a database, such as MySQL

The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php

PHP Syntax

PHP is a server-side scripting language that is used for web development. The PHP code is processed on the server, and the output is sent to the client’s browser as HTML.

Here are the basic elements of PHP syntax:

  1. Tags: PHP code is enclosed in tags <?php and ?>. Everything between these tags is interpreted as PHP code.
  2. Statements: PHP code is made up of statements that perform actions, such as assigning values to variables, looping through arrays, or outputting data to the user. A statement is usually terminated with a semicolon (;).
  3. Variables: A variable is a container for storing data that can be used in your PHP code. Variables are declared using the $ sign followed by the variable name.
  4. Comments: Comments in PHP are used to document your code or to disable certain sections of code temporarily. Comments can be single-line or multi-line, and are preceded by // or enclosed in /* and */.
  5. Functions: Functions are reusable blocks of code that can be called multiple times within your PHP script. Functions are defined using the function keyword, followed by the function name, parameters (if any), and the function body enclosed in curly braces {}.
  6. Control Structures: Control structures allow you to control the flow of your PHP script, executing code based on conditions or loops. Examples of control structures include if-else statements, switch statements, and loops such as for, while and foreach.

Here is an example of PHP code that demonstrates some of these elements:

php
<?php
// This is a single-line comment
/*
This is a
multi-line
comment
*/
$name = “John”; // variable declarationfunction sayHello($name) { // function declaration
echo “Hello, “ . $name . “!”;
}if ($name == “John”) { // if statement
sayHello($name); // function call
} else {
echo “Sorry, I don’t know you.”;
}
?>

This code declares a variable $name with the value “John”, defines a function sayHello() that takes a parameter $name and outputs a greeting message. It then checks if the variable $name is equal to “John” using an if statement, and calls the sayHello() function if the condition is true. Otherwise, it outputs a different message.

PHP Comments

In PHP, comments are used to make the code more understandable and to help other developers understand what the code is doing. There are two types of comments in PHP: single-line comments and multi-line comments.

  1. Single-Line Comments:

A single-line comment in PHP begins with two forward slashes // and continues to the end of the line. Anything after the double forward slashes will be ignored by the PHP interpreter. Here’s an example:

php
// This is a single-line comment in PHP
  1. Multi-Line Comments:

Multi-line comments in PHP begin with /* and end with */. Anything between these symbols will be ignored by the PHP interpreter. Here’s an example:

php
/*
This is a multi-line
comment in PHP
*/

Multi-line comments can be used for longer explanations of code or to temporarily disable sections of code for testing purposes. It’s also common to use multi-line comments at the beginning of a PHP file to provide an overview of what the file does and who created it.

It’s important to note that comments should be used sparingly and only when necessary. Comments should be used to explain why code is written in a certain way, not how it works. Well-written code should be self-explanatory and easy to understand without needing excessive comments.

PHP Variables

In PHP, a variable is a container for storing a value, such as a string, number, or object. PHP variables are dynamically typed, meaning you don’t need to declare the data type of a variable before assigning a value to it. Here’s the syntax for declaring a PHP variable:

php
$variable_name = value;

In this syntax, $variable_name is the name of the variable and value is the value being assigned to it. Here’s an example of declaring a variable in PHP:

php
$name = "John";
$age = 30;

In this example, the variable $name is assigned the value “John”, and the variable $age is assigned the value 30. PHP variables are case sensitive, meaning $name and $Name are two different variables.

You can also change the value of a variable by assigning a new value to it:

php
$name = "John";
$name = "Mary";

In this example, the variable $name is first assigned the value “John”, and then it is reassigned the value “Mary”.

PHP supports various data types such as string, integer, float, boolean, array, object, and more. You don’t need to specify the data type of a variable when declaring it. PHP will automatically assign the appropriate data type based on the value you assign to the variable.

Here’s an example of a variable assignment with a different data type:

php
$is_active = true; // boolean
$price = 10.99; // float
$colors = array("red", "green", "blue"); // array

In this example, $is_active is assigned the boolean value true, $price is assigned the float value 10.99, and $colors is assigned an array with three string elements.

You can also use variables in strings using concatenation or interpolation. Here’s an example:

php
$name = "John";
echo "Hello, " . $name . "!"; // using concatenation
// orecho “Hello, $name!”; // using interpolation

In this example, the variable $name is included in a string using concatenation and interpolation. The output will be “Hello, John!” in both cases.

PHP Variables Scope

In PHP, variables have different scopes, which means that they can be accessed from different parts of a script depending on where they were defined.

  1. Global Scope:

A variable declared outside of a function has a global scope, which means it can be accessed from anywhere in the script, including within functions. Here’s an example:

php

$name = "John"; // global variable

function greet() {
echo “Hello, $name!”; // accessing global variable
}

greet(); // output: Hello, John!

In this example, the variable $name is defined outside of the function greet() and is therefore in the global scope. The function greet() can access this variable and output its value.

  1. Local Scope:

A variable declared inside a function has a local scope, which means it can only be accessed within that function. Here’s an example:

php
function greet() {
$name = "John"; // local variable
echo "Hello, $name!";
}
greet(); // output: Hello, John!
echo $name; // undefined variable error

In this example, the variable $name is defined inside the function greet() and is therefore in the local scope. The function can access this variable and output its value, but outside of the function, the variable is undefined.

  1. Static Scope:

A variable declared inside a function with the static keyword has a static scope, which means it retains its value between function calls. Here’s an example:

php
function increment() {
static $count = 0; // static variable
$count++;
echo $count . "<br>";
}
increment(); // output: 1
increment(); // output: 2
increment(); // output: 3

In this example, the variable $count is declared with the static keyword, which means it retains its value between function calls. Each time the function increment() is called, the value of $count is incremented by 1 and output to the screen.

It’s important to understand variable scope in PHP to avoid conflicts and unexpected behavior in your code. In general, it’s best to limit the scope of your variables as much as possible to reduce the risk of naming conflicts or unintended side effects.

PHP echo and print Statements

Certainly! In PHP, both the echo and print statements are used to output content to the web page. They are commonly used to display text, variables, or HTML elements within PHP code. While they serve a similar purpose, there are a few differences between them.

  1. echo Statement: The echo statement is one of the most commonly used constructs in PHP. It is a language construct rather than a function, so it doesn’t require parentheses when used. It can output multiple values separated by commas.Here’s an example of using echo:
    php
    <?php
    $name = "John";
    echo "Hello, " . $name . "!"; // Output: Hello, John!
    echo "<br>"; // Output a line break
    echo "Welcome to my website.";
    ?>

    In the above example, the echo statement is used to output a greeting message and a line break. The dot (.) is used for string concatenation to combine the variable $name with the string.

  2. print Statement: The print statement is also used to output content in PHP. Unlike echo, print is a function and requires parentheses. It can only output a single value at a time and always returns 1.Here’s an example of using print:
    php
    <?php
    $age = 25;
    print("I am " . $age . " years old."); // Output: I am 25 years old.
    ?>

    In the above example, the print statement is used to output the age variable along with a descriptive string.

Both echo and print can be used interchangeably in most cases, but there are a few differences worth noting:

  • Return Value: echo doesn’t return a value, whereas print returns 1.
  • Multiple Arguments: echo can handle multiple arguments separated by commas, while print can only handle one argument.
  • Speed: echo is generally faster than print, as it doesn’t return a value.

In practice, developers often prefer using echo due to its simplicity and slightly better performance. However, both echo and print are valid options for outputting content in PHP.

PHP Data Types

Certainly! PHP supports several data types that you can use to store and manipulate different kinds of data. Here are some of the commonly used data types in PHP:

  1. String: A string represents a sequence of characters enclosed in single quotes (') or double quotes ("). Strings are used to store text.
    php
    <?php
    $name = "John Doe";
    $message = 'Hello, World!';
    ?>
  2. Integer: An integer represents a whole number without any decimal points.
    php
    <?php
    $age = 25;
    $count = 10;
    ?>
  3. Float/Double: A float or double represents a decimal number.
    php
    <?php
    $price = 9.99;
    $pi = 3.14159;
    ?>
  4. Boolean: A boolean represents a logical value, either true or false.
    php
    <?php
    $isLogged = true;
    $isWorking = false;
    ?>
  5. Array: An array is a collection of elements stored together. It can hold multiple values of different data types.
    php
    <?php
    $numbers = array(1, 2, 3, 4, 5);
    $fruits = ['apple', 'banana', 'orange'];
    ?>
  6. Object: An object represents an instance of a class and allows you to define custom data structures and methods.
    php
    <?php
    class Person {
    public $name;
    public $age;
    }
    $person = new Person();
    $person->name = “John”;
    $person->age = 25;
    ?>
  7. Null: The special value null represents the absence of any value.
    php
    <?php
    $variable = null;
    ?>

These are just a few examples of the data types available in PHP. PHP is a dynamically typed language, meaning you don’t need to explicitly declare the data type of a variable. The type is determined automatically based on the value assigned to it.

You can perform various operations and manipulate these data types using PHP’s built-in functions and operators.

PHP Strings

In PHP, strings are used to represent and manipulate textual data. They can be enclosed in either single quotes (') or double quotes ("). Here are some important aspects and operations related to strings in PHP:

  1. Creating Strings: You can create a string by enclosing text within quotes.
    php
    <?php
    $name = "John Doe"; // Using double quotes
    $message = 'Hello, World!'; // Using single quotes
    ?>
  2. String Concatenation: You can concatenate (join) strings together using the dot (.) operator.
    php
    <?php
    $firstName = "John";
    $lastName = "Doe";
    $fullName = $firstName . " " . $lastName; // Concatenating strings
    echo $fullName; // Output: John Doe
    ?>
  3. String Length: You can determine the length of a string using the strlen() function.
    php
    <?php
    $message = "Hello, World!";
    $length = strlen($message); // Length of the string
    echo $length; // Output: 13
    ?>
  4. String Manipulation: PHP provides several built-in functions for manipulating strings. Some common ones include:
    • strtolower(): Converts a string to lowercase.
    • strtoupper(): Converts a string to uppercase.
    • substr(): Extracts a portion of a string.
    • str_replace(): Replaces occurrences of a substring within a string.
    • trim(): Removes whitespace or specified characters from the beginning and end of a string.

    Here’s an example using strtolower() and str_replace():

    php
    <?php
    $message = "Hello, World!";
    $lowercase = strtolower($message); // Converts to lowercase
    echo $lowercase; // Output: hello, world!
    $replaced = str_replace(“World”, “John”, $message); // Replaces “World” with “John”
    echo $replaced; // Output: Hello, John!
    ?>
  5. String Interpolation: PHP allows you to embed variables directly within double-quoted strings, known as string interpolation.
    php
    <?php
    $name = "John Doe";
    $message = "Hello, $name!"; // Variable interpolation
    echo $message; // Output: Hello, John Doe!
    ?>
  6. Multiline Strings: In PHP, you can create multiline strings using the heredoc or nowdoc syntax.
    • Heredoc Syntax:
      php
      <?php
      $message = <<<EOT
      This is a multiline string.
      It can span multiple lines.
      EOT
      ;
      echo $message;
      ?>
    • Nowdoc Syntax:
      php
      <?php
      $message = <<<'EOT'
      This is a nowdoc string.
      It behaves similar to single quotes.
      EOT;
      echo $message;
      ?>

These are some of the common operations and features related to strings in PHP. PHP offers a rich set of string manipulation functions and methods to perform various tasks on strings.

PHP Numbers

In PHP, numbers are used to represent and perform calculations on numerical data. PHP supports different types of numbers, including integers and floating-point numbers (also known as floats or doubles). Here’s an overview of working with numbers in PHP:

  1. Integers: Integers are whole numbers without any decimal points. They can be positive or negative.
    php
    <?php
    $age = 25; // Positive integer
    $temperature = -10; // Negative integer
    ?>
  2. Floating-Point Numbers: Floating-point numbers represent numbers with decimal points. They can be expressed in decimal or scientific notation.
    php
    <?php
    $price = 9.99; // Decimal notation
    $pi = 3.14159; // Decimal notation
    $scientificNotation = 6.02e23; // Scientific notation (6.02 x 10^23)
    ?>
  3. Numeric Operations: PHP provides various arithmetic operators to perform calculations on numbers, such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
    php
    <?php
    $a = 10;
    $b = 3;
    $sum = $a + $b; // Addition
    $difference = $a$b; // Subtraction
    $product = $a * $b; // Multiplication
    $quotient = $a / $b; // Division
    $remainder = $a % $b; // Modulusecho $sum; // Output: 13
    echo $difference; // Output: 7
    echo $product; // Output: 30
    echo $quotient; // Output: 3.3333333333333
    echo $remainder; // Output: 1
    ?>
  4. Number Formatting: PHP provides functions to format numbers according to specific rules, such as number_format() to add commas as thousands separators or control decimal precision.
    php
    <?php
    $amount = 1234567.89123;
    echo number_format($amount, 2); // Output: 1,234,567.89
    ?>
  5. Mathematical Functions: PHP offers built-in mathematical functions to perform common calculations, such as rounding, absolute value, square root, logarithm, etc.
    php
    <?php
    $number = -3.75;
    echo abs($number); // Output: 3.75 (absolute value)
    echo round($number); // Output: -4 (rounded to the nearest integer)
    echo sqrt(16); // Output: 4 (square root)
    echo log(100); // Output: 4.605170185988 (natural logarithm)
    ?>

These are some of the fundamental aspects of working with numbers in PHP. PHP provides a wide range of functions and operators to handle numerical data and perform calculations.

PHP Math

In PHP, there are numerous built-in math functions available to perform mathematical operations. These functions cover a wide range of mathematical calculations. Here are some commonly used math functions in PHP:

  1. Mathematical Constants: PHP provides predefined mathematical constants such as pi (pi()), Euler’s number (exp(1)), and the golden ratio ((1 + sqrt(5)) / 2) that can be used in calculations.
    php
    <?php
    echo pi(); // Output: 3.1415926535898 (approximate value of pi)
    echo exp(1); // Output: 2.718281828459 (approximate value of Euler's number)
    echo (1 + sqrt(5)) / 2; // Output: 1.6180339887499 (approximate value of the golden ratio)
    ?>
  2. Basic Math Functions: PHP provides several basic math functions, including:
    • abs(): Returns the absolute value of a number.
    • round(): Rounds a floating-point number to the nearest integer.
    • ceil(): Rounds a number up to the nearest integer.
    • floor(): Rounds a number down to the nearest integer.
    • min(): Returns the lowest value from a list of numbers.
    • max(): Returns the highest value from a list of numbers.
    php
    <?php
    echo abs(-5); // Output: 5
    echo round(3.7); // Output: 4
    echo ceil(4.2); // Output: 5
    echo floor(7.8); // Output: 7
    echo min(5, 3, 9, 2); // Output: 2
    echo max(5, 3, 9, 2); // Output: 9
    ?>
  3. Exponentiation and Logarithmic Functions: PHP provides functions to calculate exponential and logarithmic values:
    • pow(): Calculates the value of a number raised to the power of another number.
    • sqrt(): Calculates the square root of a number.
    • exp(): Calculates the exponential value of a number.
    • log(): Calculates the natural logarithm (base e) of a number.
    php
    <?php
    echo pow(2, 3); // Output: 8 (2 raised to the power of 3)
    echo sqrt(16); // Output: 4 (square root of 16)
    echo exp(2); // Output: 7.3890560989307 (e raised to the power of 2)
    echo log(10); // Output: 2.302585092994 (natural logarithm of 10)
    ?>
  4. Trigonometric Functions: PHP provides a set of trigonometric functions for working with angles:
    • sin(): Calculates the sine of an angle.
    • cos(): Calculates the cosine of an angle.
    • tan(): Calculates the tangent of an angle.

    These functions work with radians. To work with degrees, you can use deg2rad() to convert degrees to radians.

    php
    <?php
    echo sin(deg2rad(30)); // Output: 0.5 (sine of 30 degrees)
    echo cos(deg2rad(45)); // Output: 0.70710678118655 (cosine of 45 degrees)
    echo tan(deg2rad(60)); // Output: 1.7320508075689 (tangent of 60 degrees)
    ?>

These are just a few examples of the math functions available in PHP. PHP provides a comprehensive set of math functions that cover various mathematical operations.

PHP Constants

In PHP, constants are like variables, but their values cannot be changed once they are defined. Constants are useful when you have values that need to remain consistent throughout your PHP program. Here’s how you can define and use constants in PHP:

  1. Defining Constants: You can define a constant using the define() function or the const keyword. Constants follow certain naming conventions:
    • Constants are typically written in uppercase.
    • Constants cannot start with a number.
    • Constants can contain letters, numbers, and underscores.

    Using define() function:

    php
    <?php
    define("PI", 3.14159);
    define("MAX_VALUE", 100);
    ?>

    Using const keyword (available since PHP 5.3.0):

    php
    <?php
    const PI = 3.14159;
    const MAX_VALUE = 100;
    ?>
  2. Accessing Constants: Once defined, you can access constants throughout your PHP program by simply using their name. Constants are automatically global and can be accessed from any part of your code.
    php
    <?php
    echo PI; // Output: 3.14159
    echo MAX_VALUE; // Output: 100
    ?>
  3. Magic Constants: PHP also provides a set of predefined constants called “magic constants” that change based on their usage context. These constants are prefixed with __ (double underscore).Some commonly used magic constants include:
    • __LINE__: The current line number.
    • __FILE__: The full path and filename of the current file.
    • __DIR__: The directory of the current file.
    • __FUNCTION__: The name of the current function.
    • __CLASS__: The name of the current class.
    • __METHOD__: The name of the current method.
    php
    <?php
    echo __FILE__; // Output: /path/to/file.php (current file path)
    echo __LINE__; // Output: 7 (current line number)
    echo __DIR__; // Output: /path/to (directory of the current file)
    ?>
  4. Built-in Constants: PHP provides several built-in constants that offer useful information and configuration settings. These constants are available by default and can be used in your PHP scripts.Some commonly used built-in constants include:
    • PHP_VERSION: The current PHP version.
    • PHP_OS: The operating system PHP is running on.
    • PHP_EOL: The end-of-line character for the current platform.
    • PHP_INT_MAX: The maximum value for an integer on the current platform.
    • PHP_INT_MIN: The minimum value for an integer on the current platform.
    php
    <?php
    echo PHP_VERSION; // Output: 7.4.3 (example version)
    echo PHP_OS; // Output: Linux (example OS)
    echo PHP_EOL; // Output: \n (example end of line character)
    echo PHP_INT_MAX; // Output: 9223372036854775807 (example maximum integer value)
    echo PHP_INT_MIN; // Output: -9223372036854775808 (example minimum integer value)
    ?>

Constants provide a convenient way to store and access values that should not be modified during the execution of your PHP program. They can be used to define configuration settings, mathematical constants, or any other value that needs to remain constant.

PHP Operators

In PHP, operators are used to perform various operations on variables and values. PHP supports a wide range of operators that can be classified into different categories. Here’s an overview of the commonly used operators in PHP:

  1. Arithmetic Operators: Arithmetic operators are used to perform mathematical calculations.
    • Addition: +
    • Subtraction: -
    • Multiplication: *
    • Division: /
    • Modulus (remainder): %
    • Increment: ++
    • Decrement: --
    php
    <?php
    $a = 10;
    $b = 5;
    $sum = $a + $b; // Addition
    $difference = $a$b; // Subtraction
    $product = $a * $b; // Multiplication
    $quotient = $a / $b; // Division
    $remainder = $a % $b; // Modulus$a++; // Increment by 1
    $b–; // Decrement by 1
    ?>
  2. Assignment Operators: Assignment operators are used to assign values to variables.
    • Assignment: =
    • Addition assignment: +=
    • Subtraction assignment: -=
    • Multiplication assignment: *=
    • Division assignment: /=
    • Modulus assignment: %=
    php
    <?php
    $x = 10;
    $y = 5;
    $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;
    ?>
  3. Comparison Operators: Comparison operators are used to compare values and return a Boolean result (true or false).
    • Equal to: ==
    • Identical to: ===
    • Not equal to: != or <>
    • Not identical to: !==
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
    php
    <?php
    $a = 5;
    $b = 10;
    var_dump($a == $b); // Output: bool(false)
    var_dump($a < $b); // Output: bool(true)
    var_dump($a === $b); // Output: bool(false)
    var_dump($a >= $b); // Output: bool(false)
    ?>
  4. Logical Operators: Logical operators are used to combine or negate conditions.
    • Logical AND: && or and
    • Logical OR: || or or
    • Logical NOT: ! or not
    php
    <?php
    $a = true;
    $b = false;
    var_dump($a && $b); // Output: bool(false)
    var_dump($a || $b); // Output: bool(true)
    var_dump(!$a); // Output: bool(false)
    ?>
  5. String Concatenation Operator: The string concatenation operator (.) is used to concatenate two strings together.
    php
    <?php
    $firstName = "John";
    $lastName = "Doe";
    $fullName = $firstName . ” “ . $lastName; // Concatenation
    echo $fullName; // Output: John Doe
    ?>
  6. Ternary Operator: The ternary operator (? :) provides a concise way to write conditional expressions.
    php
    <?php
    $age = 20;
    $message = ($age >= 18) ? “You are an adult” : “You are a minor”;
    echo $message; // Output: You are an adult
    ?>

These are some of the commonly used operators in PHP. PHP also provides bitwise operators, array operators, type operators, and more. Understanding and utilizing these operators allows you to perform a wide range of operations in your PHP code.

PHP if…else…else if Statements

In PHP, the if...else...else if statements are used to control the flow of execution based on certain conditions. These statements allow you to perform different actions based on whether a condition is true or false.

Here’s the general syntax of the if...else...else if statements:

php
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}

Let’s look at some examples to understand how these statements work:

Example 1:

php

$score = 85;

if ($score >= 90) {
echo “Excellent!”;
} elseif ($score >= 80) {
echo “Good job!”;
} else {
echo “You can do better.”;
}

In this example, the code checks the value of the $score variable. If the score is 90 or above, it outputs “Excellent!”. If the score is between 80 and 89, it outputs “Good job!”. Otherwise, if the score is below 80, it outputs “You can do better.”

Example 2:

php

$day = "Saturday";

if ($day == “Saturday” || $day == “Sunday”) {
echo “It’s the weekend!”;
} elseif ($day == “Friday”) {
echo “It’s Friday!”;
} else {
echo “It’s a weekday.”;
}

In this example, the code checks the value of the $day variable. If the day is “Saturday” or “Sunday”, it outputs “It’s the weekend!”. If the day is “Friday”, it outputs “It’s Friday!”. Otherwise, if the day is any other weekday, it outputs “It’s a weekday.”

You can have multiple elseif statements to check for different conditions. The else statement is optional and is executed if all preceding conditions are false

PHP switch Statement

In PHP, the switch statement is used to perform different actions based on the value of a variable or an expression. It provides an alternative way to control the flow of execution compared to multiple if...else statements. The switch statement evaluates the value of an expression and executes the code block associated with the matching case.

Here’s the general syntax of a switch statement:

php
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
case value3:
// code to be executed if expression matches value3
break;
// more case statements can be added
default:
// code to be executed if expression doesn't match any case
break;
}

Let’s see an example to understand how the switch statement works:

php

$day = "Monday";

switch ($day) {
case “Monday”:
echo “Today is Monday.”;
break;
case “Tuesday”:
echo “Today is Tuesday.”;
break;
case “Wednesday”:
echo “Today is Wednesday.”;
break;
case “Thursday”:
echo “Today is Thursday.”;
break;
case “Friday”:
echo “Today is Friday.”;
break;
default:
echo “It’s the weekend!”;
break;
}

In this example, the code checks the value of the $day variable. If the value is “Monday”, it executes the code block associated with the case "Monday" statement and outputs “Today is Monday.” If the value is “Tuesday”, it outputs “Today is Tuesday.” This process continues for each case. If none of the cases match, the code block associated with the default statement is executed, and it outputs “It’s the weekend!”

The break statement is used to terminate the execution of the switch statement once a matching case is found. Without the break statement, the code would continue to execute the subsequent cases even if they don’t match.

You can also have multiple cases with the same code block by omitting the break statement:

php

$day = "Saturday";

switch ($day) {
case “Saturday”:
case “Sunday”:
echo “It’s the weekend!”;
break;
default:
echo “It’s a weekday.”;
break;
}

In this case, if the value of $day is either “Saturday” or “Sunday”, it outputs “It’s the weekend!”

The switch statement provides a concise way to handle multiple conditions based on the value of an expression. It’s especially useful when you have a series of if...elseif statements with equality checks.

PHP Loops

In PHP, loops are used to repeatedly execute a block of code based on a certain condition. They provide a way to automate repetitive tasks and iterate over collections of data. PHP offers several types of loops: for, while, do...while, and foreach. Each loop has its own purpose and usage, allowing you to choose the most suitable one for your specific needs.

Here’s a brief introduction to each type of loop in PHP:

  1. for loop: The for loop is used when you know the number of iterations in advance. It consists of an initialization, a condition, and an increment or decrement statement. The loop continues to execute until the condition evaluates to false.
    php
    for (initialization; condition; increment/decrement) {
    // code to be executed in each iteration
    }
  2. while loop: The while loop is used when you want to repeat a block of code as long as a certain condition is true. The condition is checked before each iteration, and the loop stops executing once the condition becomes false.
    php
    while (condition) {
    // code to be executed in each iteration
    }
  3. do…while loop: The do...while loop is similar to the while loop, but the condition is checked after each iteration. This guarantees that the block of code is executed at least once, even if the condition is initially false.
    php
    do {
    // code to be executed in each iteration
    } while (condition);
  4. foreach loop: The foreach loop is used to iterate over arrays or other iterable objects. It allows you to access each element of the collection without explicitly managing an index or counter.
    php
    foreach ($array as $value) {
    // code to be executed for each element
    }

These loops can be combined with conditional statements (if, else, elseif) to control the flow of execution within the loop.

Here’s a simple example that demonstrates the usage of a for loop to iterate from 1 to 5 and display the current value:

php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5

Loops are powerful constructs in PHP that help make your code more efficient and flexible. They allow you to perform repetitive tasks, process large amounts of data, and create dynamic behavior in your programs.

PHP Break and Continue

In PHP, the break and continue statements are used within loops to control the flow of execution.

  1. break statement: The break statement is used to terminate the execution of a loop prematurely. When the break statement is encountered, the loop immediately exits, and the program continues with the next statement after the loop.Here’s an example of using break within a for loop:
    php
    for ($i = 1; $i <= 10; $i++) {
    if ($i == 6) {
    break;
    }
    echo $i . " ";
    }
    // Output: 1 2 3 4 5

    In this example, the loop iterates from 1 to 10. When the value of $i becomes 6, the break statement is encountered, and the loop is terminated. Therefore, only the numbers 1 to 5 are displayed.

  2. continue statement: The continue statement is used to skip the remaining code within a loop for the current iteration and move to the next iteration.Here’s an example of using continue within a while loop:
    php
    $i = 0;
    while ($i < 5) {
    $i++;
    if ($i == 3) {
    continue;
    }
    echo $i . " ";
    }
    // Output: 1 2 4 5

    In this example, the loop iterates while the value of $i is less than 5. When the value of $i becomes 3, the continue statement is encountered. As a result, the code after continue is skipped, and the loop moves on to the next iteration. Therefore, the number 3 is not displayed.

The break and continue statements provide flexibility within loops and allow you to control the execution based on certain conditions. They are useful for implementing conditional behavior and handling specific cases in loops.

It’s important to note that break and continue statements can be used within for, while, do...while, and foreach loops in PHP.

PHP Functions

In PHP, functions are blocks of code that can be reused to perform specific tasks. They provide a way to organize and modularize your code, making it more manageable, readable, and reusable. Functions help avoid code duplication and promote code reusability across different parts of your program.

Here’s a brief introduction to creating and using functions in PHP:

  1. Function declaration: To create a function, you need to declare it using the function keyword, followed by the function name and parentheses. Any parameters (inputs) that the function requires are listed within the parentheses.
    php
    function functionName($param1, $param2) {
    // code to be executed
    }
  2. Function parameters: Functions can accept parameters that allow you to pass values to the function when it is called. Parameters are specified within the function declaration and can be used within the function’s code block.
    php
    function greet($name) {
    echo "Hello, " . $name . "!";
    }
    greet(“John”);
    // Output: Hello, John!

    In this example, the greet() function takes a single parameter $name. When the function is called with the argument “John”, it outputs “Hello, John!”.

  3. Function return value: Functions can also return values using the return statement. The return statement allows you to send a value back to the code that called the function. After the return statement is executed, the function terminates.
    php
    function add($num1, $num2) {
    return $num1 + $num2;
    }
    $result = add(5, 3);
    echo $result;
    // Output: 8

    In this example, the add() function takes two parameters $num1 and $num2, and it returns the sum of the two numbers. The returned value is assigned to the variable $result, which is then echoed.

  4. Function invocation: To execute a function, you simply call it by its name, followed by parentheses. If the function requires parameters, you pass the values within the parentheses.
    php
    functionName($arg1, $arg2);

    For example:

    php
    greet("Alice");

    This line of code calls the greet() function and passes the argument “Alice”.

Functions can be defined anywhere in your PHP code, and they can be called multiple times from different parts of your program. This allows you to encapsulate logic and perform specific tasks without duplicating code.

PHP also provides built-in functions that cover a wide range of functionalities, such as manipulating strings, working with arrays, performing mathematical calculations, interacting with databases, and more. These built-in functions save time and effort by providing ready-to-use solutions.

PHP Arrays

In PHP, an array is a data structure that allows you to store and organize multiple values in a single variable. Arrays are incredibly versatile and widely used in PHP to handle collections of data.

Here’s a brief introduction to arrays in PHP:

  1. Creating an array: You can create an array in PHP using the array() function or using the shorthand square bracket notation [].
    php

    $fruits = array("Apple", "Banana", "Orange");

    // or

    $fruits = [“Apple”, “Banana”, “Orange”];

    In this example, we create an array named $fruits that stores three elements: “Apple”, “Banana”, and “Orange”.

  2. Accessing array elements: Array elements can be accessed using their index, which starts from 0. You can retrieve an element by specifying the index within square brackets.
    php
    echo $fruits[0]; // Output: Apple

    In this example, we access the first element of the $fruits array and output its value, which is “Apple”.

  3. Modifying array elements: You can change the value of an array element by assigning a new value to the corresponding index.
    php
    $fruits[1] = "Mango";
    echo $fruits[1]; // Output: Mango

    In this example, we modify the value of the second element in the $fruits array and output the updated value, which is now “Mango”.

  4. Array functions: PHP provides a variety of built-in functions to work with arrays. Some common functions include:
    • count(): Returns the number of elements in an array.
    • array_push(): Adds one or more elements to the end of an array.
    • array_pop(): Removes and returns the last element of an array.
    • array_merge(): Combines two or more arrays into a single array.

    These are just a few examples, and there are many more array functions available in PHP.

  5. Iterating through arrays: You can iterate through the elements of an array using loops, such as for or foreach. The foreach loop is particularly useful for iterating over each element of an array without explicitly managing the index.
    php
    foreach ($fruits as $fruit) {
    echo $fruit . " ";
    }
    // Output: Apple Banana Mango

    In this example, we use a foreach loop to iterate through each element of the $fruits array and output its value.

Arrays in PHP can also be multidimensional, allowing you to create arrays of arrays, providing more complex data structures.

Arrays are a fundamental data structure in PHP and are used extensively to store, manipulate, and process collections of data. They offer great flexibility and enable efficient data management in PHP applications.

PHP Indexed Arrays

In PHP, an indexed array is a type of array where each element is assigned a numerical index starting from 0. It is the most basic and commonly used type of array. Indexed arrays allow you to store and access multiple values using their numeric positions.

Here’s an example of creating and working with indexed arrays in PHP:

  1. Creating an indexed array: You can create an indexed array by assigning values to each element using the array() function or the square bracket notation [].
    php

    $fruits = array("Apple", "Banana", "Orange");

    // or

    $fruits = [“Apple”, “Banana”, “Orange”];

    In this example, we create an indexed array named $fruits with three elements: “Apple”, “Banana”, and “Orange”.

  2. Accessing array elements: You can access individual elements of an indexed array by specifying their index within square brackets.
    php
    echo $fruits[0]; // Output: Apple
    echo $fruits[1]; // Output: Banana
    echo $fruits[2]; // Output: Orange

    In this example, we access and output the values of the first, second, and third elements in the $fruits array.

  3. Modifying array elements: You can modify the value of an element in an indexed array by assigning a new value to its corresponding index.
    php
    $fruits[1] = "Mango";
    echo $fruits[1]; // Output: Mango

    In this example, we update the value of the second element in the $fruits array to “Mango” and output the updated value.

  4. Array functions: PHP provides several built-in functions to work with indexed arrays. Some common functions include:
    • count(): Returns the number of elements in an array.
    • array_push(): Adds one or more elements to the end of an array.
    • array_pop(): Removes and returns the last element of an array.
    • array_merge(): Combines two or more arrays into a single array.

    These functions can be used to manipulate and perform operations on indexed arrays.

  5. Iterating through an indexed array: You can iterate through the elements of an indexed array using loops, such as for or foreach. The foreach loop is commonly used to iterate through each element of an indexed array without needing to manage the index explicitly.
    php
    foreach ($fruits as $fruit) {
    echo $fruit . " ";
    }
    // Output: Apple Banana Mango

    In this example, we use a foreach loop to iterate through each element of the $fruits array and output its value.

Indexed arrays are versatile and widely used in PHP to store and process collections of values. They provide a straightforward and efficient way to manage ordered data.

PHP Associative Arrays

In PHP, an associative array is a type of array where each element is associated with a unique key instead of a numerical index. Unlike indexed arrays, associative arrays allow you to use custom keys to access and manipulate values. The key-value pairs in an associative array provide a convenient way to store and retrieve data based on descriptive labels.

Here’s a brief explanation of associative arrays in PHP:

  1. Creating an associative array: You can create an associative array by assigning values to specific keys using the array() function or the square bracket notation [].
    php
    $student = array(
    "name" => "John",
    "age" => 20,
    "grade" => "A"
    );
    // or$student = [
    “name” => “John”,
    “age” => 20,
    “grade” => “A”
    ];

    In this example, we create an associative array named $student with three key-value pairs: “name” => “John”, “age” => 20, and “grade” => “A”.

  2. Accessing array elements: You can access individual elements of an associative array by specifying their key within square brackets.
    php
    echo $student["name"]; // Output: John
    echo $student["age"]; // Output: 20
    echo $student["grade"]; // Output: A

    In this example, we access and output the values of the “name”, “age”, and “grade” keys in the $student array.

  3. Modifying array elements: You can modify the value of an element in an associative array by assigning a new value to its corresponding key.
    php
    $student["age"] = 21;
    echo $student["age"]; // Output: 21

    In this example, we update the value of the “age” key in the $student array to 21 and output the updated value.

  4. Array functions: PHP provides various built-in functions to work with associative arrays. Some common functions include:
    • count(): Returns the number of elements in an array.
    • array_keys(): Returns an array of all the keys in an associative array.
    • array_values(): Returns an array of all the values in an associative array.
    • array_merge(): Combines two or more arrays into a single array.

    These functions can be used to manipulate and perform operations on associative arrays.

  5. Iterating through an associative array: You can iterate through the elements of an associative array using loops, such as foreach. The foreach loop is commonly used to iterate through each key-value pair of an associative array.
    php
    foreach ($student as $key => $value) {
    echo $key . ": " . $value . "<br>";
    }
    // Output:
    // name: John
    // age: 20
    // grade: A

    In this example, we use a foreach loop to iterate through each key-value pair of the $student array and output the key and its corresponding value.

Associative arrays in PHP provide a flexible and intuitive way to organize and retrieve data based on meaningful keys. They are particularly useful when you need to associate specific information with descriptive labels.

PHP Multidimensional Arrays

In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These arrays can be either indexed arrays or associative arrays. Multidimensional arrays provide a way to organize complex data structures that involve multiple levels or dimensions.

Here’s a brief explanation of multidimensional arrays in PHP:

  1. Creating a multidimensional array: You can create a multidimensional array by nesting one or more arrays within another array.
    php
    $students = array(
    array("John", 20, "A"),
    array("Jane", 19, "B"),
    array("David", 21, "A")
    );

    In this example, we create a multidimensional array named $students where each element is an indexed array representing a student’s name, age, and grade.

  2. Accessing array elements: You can access individual elements of a multidimensional array by specifying their indices or keys at each level using multiple sets of square brackets.
    php
    echo $students[0][0]; // Output: John
    echo $students[1][1]; // Output: 19
    echo $students[2][2]; // Output: A

    In this example, we access and output the values of specific elements in the $students array using their indices.

  3. Modifying array elements: You can modify the value of an element in a multidimensional array by assigning a new value to its corresponding indices or keys.
    php
    $students[1][2] = "A";
    echo $students[1][2]; // Output: A

    In this example, we update the value of the grade for the second student in the $students array and output the updated value.

  4. Iterating through a multidimensional array: You can iterate through the elements of a multidimensional array using nested loops, such as for or foreach, to access each level of the array.
    php
    foreach ($students as $student) {
    foreach ($student as $value) {
    echo $value . " ";
    }
    echo "<br>";
    }
    // Output:
    // John 20 A
    // Jane 19 B
    // David 21 A

    In this example, we use nested foreach loops to iterate through each student in the $students array and output their name, age, and grade.

Multidimensional arrays in PHP allow you to represent hierarchical or tabular data structures. They are commonly used to store and manipulate data that has multiple dimensions or levels of organization.

PHP Sorting Arrays

In PHP, you can sort arrays using various sorting functions. These functions allow you to arrange the elements of an array in a specific order, such as ascending or descending. Here are some commonly used sorting functions in PHP:

  1. sort(): The sort() function sorts an array in ascending order based on the values of its elements. The keys of the array are not preserved.
    php
    $numbers = [3, 1, 4, 2, 5];
    sort($numbers);
    print_r($numbers);
    // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
  2. rsort(): The rsort() function sorts an array in descending order based on the values of its elements. The keys of the array are not preserved.
    php
    $numbers = [3, 1, 4, 2, 5];
    rsort($numbers);
    print_r($numbers);
    // Output: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
  3. asort(): The asort() function sorts an array in ascending order based on the values of its elements. The keys of the array are preserved.
    php
    $fruits = ["Apple" => 3, "Banana" => 1, "Orange" => 2];
    asort($fruits);
    print_r($fruits);
    // Output: Array ( [Banana] => 1 [Orange] => 2 [Apple] => 3 )
  4. arsort(): The arsort() function sorts an array in descending order based on the values of its elements. The keys of the array are preserved.
    php
    $fruits = ["Apple" => 3, "Banana" => 1, "Orange" => 2];
    arsort($fruits);
    print_r($fruits);
    // Output: Array ( [Apple] => 3 [Orange] => 2 [Banana] => 1 )
  5. ksort(): The ksort() function sorts an array in ascending order based on the keys of its elements. The values of the array are preserved.
    php
    $fruits = ["Apple" => 3, "Banana" => 1, "Orange" => 2];
    ksort($fruits);
    print_r($fruits);
    // Output: Array ( [Apple] => 3 [Banana] => 1 [Orange] => 2 )
  6. krsort(): The krsort() function sorts an array in descending order based on the keys of its elements. The values of the array are preserved.
    php
    $fruits = ["Apple" => 3, "Banana" => 1, "Orange" => 2];
    krsort($fruits);
    print_r($fruits);
    // Output: Array ( [Orange] => 2 [Banana] => 1 [Apple] => 3 )

These are just a few examples of sorting functions available in PHP. You can choose the appropriate function based on your specific sorting requirements. Additionally, PHP provides more advanced sorting functions, such as usort() and uasort(), which allow you to define custom comparison logic for sorting arrays.

PHP Global Variables – Superglobals

In PHP, global variables are variables that can be accessed from anywhere in a script, including inside functions, without the need to explicitly declare them as global within each function. PHP provides a set of special variables called superglobals, which are predefined and accessible in all scopes throughout a script. These superglobals allow you to access and manipulate various information and data within your PHP scripts.

Here are some examples of commonly used PHP superglobals:

  1. $GLOBALS: The $GLOBALS superglobal is an associative array that contains references to all variables available in the global scope. By accessing this array, you can access and modify global variables directly.
    php

    $name = "John";

    function printName() {
    echo $GLOBALS[‘name’];
    }

    printName(); // Output: John

    In this example, the $GLOBALS superglobal is used to access the global variable $name inside the printName() function.

  2. $_SERVER: The $_SERVER superglobal contains information about the server and execution environment. It provides access to various server and request-related details such as the URL, request method, user agent, and more.
    php
    echo $_SERVER['SERVER_NAME']; // Output: example.com
    echo $_SERVER['REQUEST_METHOD']; // Output: GET
    echo $_SERVER['REMOTE_ADDR']; // Output: 127.0.0.1

    In this example, we access and output the server name, request method, and remote IP address using the $_SERVER superglobal.

  3. $_GET and $_POST: The $_GET and $_POST superglobals are used to retrieve data sent via the HTTP GET and POST methods, respectively. They contain key-value pairs of data from the URL query parameters or form submissions.
    php
    // URL: example.com?name=John
    echo $_GET['name']; // Output: John
    // HTML form: <input type=”text” name=”username”>
    echo $_POST[‘username’]; // Output: (value entered in the form)

    In these examples, we retrieve and output data passed through the URL query parameter ($_GET) and a form field submission ($_POST).

  4. $_SESSION: The $_SESSION superglobal is used to store and access session-specific data. It enables you to persist data across multiple pages or requests for a specific user session.
    php

    session_start(); // Start the session

    $_SESSION[‘user_id’] = 123; // Set a session variable

    echo $_SESSION[‘user_id’]; // Output: 123

    In this example, we set a session variable using the $_SESSION superglobal and then retrieve and output its value.

  5. $_COOKIE: The $_COOKIE superglobal contains data stored in cookies sent by the browser. Cookies are small pieces of data stored on the client side that can be accessed and manipulated by the server.
    php
    echo $_COOKIE['username']; // Output: (value stored in the 'username' cookie)

    In this example, we access and output the value of a cookie named ‘username’ using the $_COOKIE superglobal.

These are just a few examples of PHP superglobals. Other superglobals include $_REQUEST, $_FILES, and $_ENV, each serving specific purposes for accessing and manipulating different types of data and information.

By utilizing these superglobals, you can access and work with global data and environment information easily in PHP, providing you with flexibility and convenience in your script development.

PHP Regular Expressions

In PHP, regular expressions (often referred to as regex or regexp) are powerful tools for pattern matching and manipulation of strings. Regular expressions are sequences of characters that define a search pattern, allowing you to perform complex string operations such as finding, replacing, and extracting specific patterns of text.

PHP provides several functions for working with regular expressions, including:

  1. preg_match(): This function is used to perform a regular expression match against a string. It returns true if a match is found, and false otherwise.
    php
    $str = "Hello, World!";
    if (preg_match("/Hello/", $str)) {
    echo "Match found!";
    } else {
    echo "No match found!";
    }
    // Output: Match found!

    In this example, we use preg_match() to check if the string contains the word “Hello”.

  2. preg_replace(): This function is used to perform a search and replace using a regular expression pattern. It replaces all occurrences of the pattern with a specified replacement string.
    php
    $str = "Hello, World!";
    $newStr = preg_replace("/Hello/", "Hi", $str);
    echo $newStr;
    // Output: Hi, World!

    In this example, we use preg_replace() to replace the word “Hello” with “Hi” in the string.

  3. preg_match_all(): This function is similar to preg_match(), but it returns all matches found in the string as an array.
    php
    $str = "The quick brown fox jumps over the lazy dog.";
    $matches = [];
    preg_match_all("/\b\w{4}\b/", $str, $matches);
    print_r($matches[0]);
    // Output: Array ( [0] => quick [1] => over lazy )

    In this example, we use preg_match_all() to find all four-letter words in the string.

These are just a few examples of using regular expressions in PHP. Regular expressions provide a versatile and powerful way to search, manipulate, and validate strings based on specific patterns.

When working with regular expressions in PHP, you can use various metacharacters, quantifiers, character classes, and other constructs to define your patterns. It’s worth noting that PHP uses the PCRE (Perl Compatible Regular Expressions) library, which supports a rich set of regular expression features.

If you’re new to regular expressions, it may take some time and practice to become familiar with their syntax and capabilities. However, they can greatly enhance your ability to handle complex string operations in PHP. You can refer to the PHP documentation for more detailed information and examples on working with regular expressions: https://www.php.net/manual/en/book.pcre.php

Scroll to Top