PHP Tutorial

Learn PHP programming from scratch with our comprehensive tutorial

PHP Introduction

PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

What is PHP?

  • PHP is a server-side scripting language
  • 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?

  • Generate dynamic page content
  • Create, open, read, write, delete, and close files on the server
  • Collect form data
  • Send and receive cookies
  • Add, delete, modify data in your database
  • Control user-access
  • Encrypt data

PHP Syntax

A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>.

Example
<?php
// PHP code goes here
?>

Basic PHP Syntax

  • PHP statements end with a semicolon (;)
  • PHP code must be inside <?php ?> tags
  • PHP files must have a .php extension
  • PHP is case-sensitive

PHP Variables

Variables are containers for storing data. In PHP, a variable starts with the $ sign, followed by the name of the variable.

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

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)

Echo and Print

In PHP, there are two basic ways to get output: echo and print. Both are used to output data to the screen.

Example
<?php
echo "Hello World!";
print "Hello World!";
?>

Differences between echo and print:

  • echo has no return value while print has a return value of 1
  • echo can take multiple parameters while print can take one argument
  • echo is marginally faster than print

PHP Data Types

PHP supports the following data types:

String

Example
<?php
$string = "Hello World!";
?>

Integer

Example
<?php
$int = 5985;
?>

Float (floating point numbers)

Example
<?php
$float = 10.365;
?>

Boolean

Example
<?php
$bool = true;
?>

Array

Example
<?php
$array = array("Volvo", "BMW", "Toyota");
?>

Object

Example
<?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");
?>

PHP Control Structures

Control structures are used to control the flow of execution in a program.

If Statement

Example
<?php
if ($a > $b) {
    echo "a is greater than b";
}
?>

If...Else Statement

Example
<?php
if ($a > $b) {
    echo "a is greater than b";
} else {
    echo "b is greater than a";
}
?>

Switch Statement

Example
<?php
switch ($color) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    default:
        echo "Your favorite color is neither red nor blue!";
}
?>

PHP Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

While Loop

Example
<?php
$i = 1;
while ($i <= 5) {
    echo "The number is: $i <br>";
    $i++;
}
?>

Do...While Loop

Example
<?php
$i = 1;
do {
    echo "The number is: $i <br>";
    $i++;
} while ($i <= 5);
?>

For Loop

Example
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "The number is: $i <br>";
}
?>

Foreach Loop

Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
    echo "$value <br>";
}
?>

PHP Functions

A function is a block of statements that can be used repeatedly in a program.

Creating a Function

Example
<?php
function writeMsg() {
    echo "Hello world!";
}
writeMsg();
?>

Function Arguments

Example
<?php
function familyName($fname) {
    echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
?>

Return Values

Example
<?php
function sum($x, $y) {
    return $x + $y;
}
echo "5 + 10 = " . sum(5, 10);
?>

PHP Arrays

An array stores multiple values in one single variable.

Indexed Arrays

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Associative Arrays

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Multidimensional Arrays

Example
<?php
$cars = array (
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2),
    array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2]."<br>";
?>

PHP Superglobals

Superglobals are built-in variables that are always available in all scopes.

Common Superglobals

  • $GLOBALS - References all variables available in global scope
  • $_SERVER - Contains information about the server and execution environment
  • $_REQUEST - Contains data from $_GET, $_POST, and $_COOKIE
  • $_POST - Contains data from POST requests
  • $_GET - Contains data from GET requests
  • $_FILES - Contains information about uploaded files
  • $_ENV - Contains environment variables
  • $_COOKIE - Contains HTTP cookies
  • $_SESSION - Contains session variables

Example of $_GET

Example
<?php
echo "Hello " . $_GET['name'];
// URL: page.php?name=John
?>

Example of $_POST

Example
<?php
echo "Hello " . $_POST['name'];
// Form submission with name field
?>

PHP Regular Expressions

Regular expressions are patterns used to match character combinations in strings.

Common Functions

  • preg_match() - Returns 1 if pattern matches, 0 if not
  • preg_match_all() - Returns number of matches
  • preg_replace() - Replaces matches with replacement

Basic Patterns

Example
<?php
// Check if string contains "php"
if (preg_match("/php/i", "PHP is fun!")) {
    echo "Match found!";
}

// Replace all occurrences of "php" with "PHP"
$str = "Visit php!";
$str = preg_replace("/php/i", "PHP", $str);
echo $str;
?>

Common Patterns

  • /[abc]/ - Matches any single character in the brackets
  • /[^abc]/ - Matches any single character not in the brackets
  • /[0-9]/ - Matches any single digit
  • /[a-z]/ - Matches any single lowercase letter
  • /[A-Z]/ - Matches any single uppercase letter
  • /[a-zA-Z]/ - Matches any single letter
  • /^/ - Matches start of string
  • /$/ - Matches end of string