Skip to content
DevNursery.com - New Web Developer Docs
GitHub

PHP

Basic Syntax of PHP

PHP (Hypertext Preprocessor) is a widely-used, open-source scripting language primarily designed for web development. It can be embedded within HTML or used to create standalone scripts. Let’s explore the basic syntax of PHP:

1. PHP Tags

PHP code is embedded within HTML or can be written as standalone scripts. To start a PHP block, you use PHP tags:

<?php
// PHP code goes here
?>

Alternatively, you can also use short tags for PHP, but these might not be enabled on all servers:

<?
// PHP code goes here
?>

2. Comments

PHP supports both single-line and multi-line comments:

// This is a single-line comment

/*
   This is a
   multi-line comment
*/

3. Outputting Text

You can use the echo or print statements to output text or HTML content to the browser:

echo "Hello, World!";
print "Welcome to PHP!";

4. Variables

In PHP, variables start with the $ symbol, followed by the variable name. Variable names are case-sensitive:

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

5. Data Types

PHP supports various data types, including integers, floats, strings, booleans, arrays, and more:

$integerVar = 42;
$floatVar = 3.14;
$stringVar = "Hello, PHP!";
$boolVar = true;

6. Concatenation

You can concatenate strings using the . (dot) operator:

$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
  1. Conditional Statements PHP supports conditional statements like if, else if, and else:
if ($age < 18) {
    echo "You are a minor.";
} elseif ($age >= 18 && $age < 60) {
    echo "You are an adult.";
} else {
    echo "You are a senior citizen.";
}

8. Loops

You can create loops in PHP using for, while, do-while, and foreach:

for ($i = 1; $i <= 5; $i++) {
    echo "Iteration $i <br>";
}

$counter = 0;
while ($counter < 3) {
    echo "While loop iteration $counter <br>";
    $counter++;
}

$counter = 0;
do {
    echo "Do-while loop iteration $counter <br>";
    $counter++;
} while ($counter < 3);

$fruits = array("apple", "banana", "cherry");
foreach ($fruits as $fruit) {
    echo "I like $fruit <br>";
}

9. Functions

You can define functions in PHP using the function keyword:

function greet($name) {
    echo "Hello, $name!";
}

greet("Alice"); // Outputs: Hello, Alice!

10. Include and Require

PHP allows you to include or require external files within your script:

include 'header.php'; // Include a file
require 'footer.php'; // Require a file (terminates script on failure)

11. Superglobals

Superglobals are pre-defined global arrays that provide access to global variables in PHP:

  • $_GET: Access query string parameters.
  • $_POST: Access POST data.
  • $_SESSION: Access session variables.
  • $_COOKIE: Access cookies.
  • $_SERVER: Access server and execution environment information.

PHP Functions

Functions in PHP allow you to encapsulate a block of code that can be reused throughout your script. They help make your code more modular and maintainable. Here’s a detailed look at PHP functions:

Function Syntax

In PHP, you define a function using the function keyword, followed by the function name, a pair of parentheses, and a block of code enclosed in curly braces {}. Here’s the basic syntax:

function functionName(parameters) {
    // Function code here
}
  • function: Keyword to declare a function.
  • functionName: Name of the function.
  • parameters: Optional input parameters the function can accept.
  • {}: Encloses the function body.

Function Arguments

Functions can accept zero or more arguments (input parameters). You specify the arguments within the parentheses when defining the function. Here’s an example of a function with arguments:

function greet($name) {
    echo "Hello, $name!";
}

In the above example, the $name is a parameter, and you can pass a value when calling the function:

greet("Alice"); // Outputs: Hello, Alice!

Return Values

Functions can also return values using the return statement. The returned value can be of any data type. Here’s an example of a function that returns a value:

function add($a, $b) {
    return $a + $b;
}

You can call the function and capture its return value:

$result = add(5, 3); // $result will hold the value 8

Arrow Functions (PHP 7.4+)

PHP 7.4 introduced arrow functions, a more concise way to define small, inline functions. Arrow functions are especially useful for anonymous functions with simple logic. Here’s the syntax:

$add = fn($a, $b) => $a + $b;

In the above example, $add is an arrow function that takes two arguments and returns their sum. Arrow functions automatically capture variables from the surrounding scope.

You can use arrow functions wherever you would use anonymous functions. They are shorter and more readable when dealing with simple operations.

Example: Using Arrow Functions

$numbers = [1, 2, 3, 4, 5];

// Using an arrow function to filter even numbers
$evens = array_filter($numbers, fn($num) => $num % 2 === 0);

// Using an arrow function to double each number
$doubled = array_map(fn($num) => $num * 2, $numbers);

print_r($evens);   // Outputs: Array ( [1] => 2 [3] => 4 )
print_r($doubled); // Outputs: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

Arrow functions make the code more concise and easier to read, especially when working with array functions like array_map and array_filter.

These are the fundamentals of working with functions in PHP. Functions play a crucial role in organizing and reusing code in your PHP applications, and arrow functions offer a modern and efficient way to define small, inline functions in PHP 7.4 and later versions.

PHP Classes

In PHP, a class is a blueprint for creating objects, which are instances of that class. Classes are fundamental to object-oriented programming (OOP) and allow you to encapsulate data and behavior into reusable and structured units. Here’s a detailed look at PHP classes:

Class Definition

You define a class using the class keyword, followed by the class name and a pair of curly braces {} that enclose the class’s properties and methods. Here’s the basic syntax of a class definition:

class ClassName {
    // Properties (variables)
    // Methods (functions)
}
  • class: Keyword to declare a class.
  • ClassName: Name of the class (should start with an uppercase letter).

Properties (Variables)

Properties are variables defined within a class and are used to store data associated with objects created from that class. They are often called “attributes” or “fields” in other programming languages. To declare a property, you use the public, protected, or private keyword followed by the variable name. Here’s how you declare properties:

class Person {
    public $name;      // Public property
    protected $age;    // Protected property
    private $email;    // Private property
}
  • public: Accessible from anywhere (outside the class).
  • protected: Accessible only within the class and its subclasses.
  • private: Accessible only within the class itself.

Methods (Functions)

Methods are functions defined within a class and are used to perform actions or operations related to the class. They are similar to regular functions but are associated with objects created from the class. To declare a method, you use the public, protected, or private keyword followed by the function definition. Here’s how you declare methods:

class Car {
    public function startEngine() {
        // Method code here
    }

    protected function accelerate() {
        // Method code here
    }

    private function stopEngine() {
        // Method code here
    }
}
  • public: Accessible from anywhere (outside the class).
  • protected: Accessible only within the class and its subclasses.
  • private: Accessible only within the class itself.

Constructors

A constructor is a special method that gets called automatically when an object is created from a class. In PHP, the constructor method is named __construct(). You can use it to initialize object properties or perform any setup required when an object is created. Here’s how to define a constructor:

class Product {
    public $name;

    public function __construct($productName) {
        $this->name = $productName;
    }
}

When you create an object from the Product class, the constructor will be executed:

$product = new Product("Widget");
echo $product->name; // Outputs: Widget

Creating Objects

To create an object (an instance) from a class, you use the new keyword followed by the class name and parentheses. Here’s how to create objects:

$car1 = new Car();
$car2 = new Car();

Now you have two separate instances of the Car class, $car1 and $car2.

Inheritance

Inheritance is a fundamental concept in OOP that allows you to create a new class based on an existing class. The new class (called the subclass or child class) inherits properties and methods from the existing class (called the superclass or parent class). In PHP, you use the extends keyword for inheritance:

class ChildClass extends ParentClass {
    // Additional properties and methods
}

Overriding Methods

When a subclass inherits a method from a parent class but wants to provide its own implementation of that method, it can override the method. This is done by defining a method in the subclass with the same name and parameters as the parent class’s method.

Here’s an example:

class Animal {
    public function speak() {
        echo "Animal speaks";
    }
}

class Dog extends Animal {
    public function speak() {
        echo "Woof!";
    }
}

Now, when you create an instance of Dog and call the speak() method, it will override the parent class’s method:

$dog = new Dog();
$dog->speak(); // Outputs: Woof!

Static Methods and Properties In addition to instance methods and properties, you can define static methods and properties in a class. Static methods and properties are associated with the class itself, rather than with instances of the class. You declare them using the static keyword:

class MathUtils {
    public static function add($a, $b) {
        return $a + $b;
    }

    public static $pi = 3.14159265359;
}

You can call static methods and access static properties without creating an object:

$result = MathUtils::add(5, 3); // $result will hold the value 8
$piValue = MathUtils::$pi;       // $piValue will hold the value 3.14159265359

PHP Command-Line Interface (CLI)

The PHP Command-Line Interface (CLI) allows you to run PHP scripts and perform various tasks directly from the terminal or command prompt. It provides a powerful way to execute PHP code outside of a web server context. Here are some common use cases and commands when working with the PHP CLI:

Running a PHP File

You can execute a PHP script file by simply running the php command followed by the name of the script file. For example:

php myscript.php

This command will execute the PHP code in the myscript.php file.

Accessing the PHP REPL

PHP provides a Read-Eval-Print Loop (REPL) mode, which allows you to interactively execute PHP code in a command-line environment. To access the PHP REPL, open your terminal and run:

php -a

You’ll enter an interactive shell where you can type and execute PHP code line by line. To exit the REPL, use the exit or quit command or press Ctrl + D.

Running a Web Server

PHP CLI also includes a built-in web server that is useful for local development and testing. You can start the web server from the command line like this:

php -S localhost:8000

This command starts a web server on localhost at port 8000, serving files from the current directory. You can access your PHP files in a web browser at http://localhost:8000.

Using Composer for Dependency Management

Composer is a dependency management tool for PHP that simplifies the process of adding and managing packages (libraries and frameworks) in your PHP projects. To use Composer with PHP CLI:

Install Composer globally on your system by following the instructions on the Composer website.

Create a composer.json file in your project directory. This file defines the dependencies for your project. Here’s an example of a composer.json file:

{
    "require": {
        "monolog/monolog": "^2.0"
    }
}

Use the composer install command to download and install the specified dependencies:

composer install

Composer will create a vendor directory in your project, where it stores the installed packages.

You can autoload Composer dependencies in your PHP scripts by including the vendor/autoload.php file:

require 'vendor/autoload.php';

Now, you can use the packages you installed via Composer in your PHP scripts.

Syntax of a composer.json File

A composer.json file is used to define project metadata and dependencies. Here are some key elements of a composer.json file:

  • name: The name of your project.
  • description: A brief description of your project.
  • type: The type of your project (e.g., “library,” “project,” “metapackage”).
  • require: Specifies the required packages and their versions.
  • require-dev: Specifies development dependencies (e.g., testing tools).
  • autoload: Defines autoloading rules for your project’s classes.
  • scripts: Allows you to define custom scripts to run during Composer actions.

Here’s an example of a composer.json file:

{
    "name": "your/awesome-project",
    "description": "An amazing PHP project",
    "type": "project",
    "require": {
        "monolog/monolog": "^2.0",
        "doctrine/orm": "^2.8"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.0"
    },
    "autoload": {
        "psr-4": {
            "YourNamespace\\": "src/"
        }
    },
    "scripts": {
        "post-install-cmd": "php artisan migrate",
        "post-update-cmd": "php artisan migrate"
    }
}

PHP Built-in Functions

1-25

FunctionPurposeSyntaxExample
echoOutput textecho string, ...echo "Hello, world!";
strlenGet string lengthstrlen(string)echo strlen("PHP is powerful");
str_replaceReplace part of a stringstr_replace(search, replace, subject)echo str_replace("world", "PHP", "Hello, world!");
substrGet part of a stringsubstr(string, start, length)echo substr("Hello, world!", 0, 5);
implode / joinJoin array elementsimplode(glue, array)echo implode(", ", ["apple", "banana", "cherry"]);
explodeSplit a string into an arrayexplode(delimiter, string)$fruits = explode(", ", "apple, banana, cherry");
countCount array elementscount(array, mode)echo count([1, 2, 3]);
array_pushAdd elements to an arrayarray_push(array, value1, ...)array_push($stack, "apple", "banana");
array_popRemove and return the last element of an arrayarray_pop(array)$lastItem = array_pop($stack);
array_mergeMerge arraysarray_merge(array1, array2, ...)$merged = array_merge($arr1, $arr2);
sortSort an arraysort(array, sort_flags)sort($fruits);
randGenerate random numberrand(min, max)$random = rand(1, 10);
dateFormat date and timedate(format, timestamp)echo date("Y-m-d H:i:s");
timeGet current Unix timestamptime()$timestamp = time();
file_get_contentsRead a file into a stringfile_get_contents(filename)$content = file_get_contents("file.txt");
file_put_contentsWrite a string to a filefile_put_contents(filename, data)file_put_contents("file.txt", "Hello, PHP!");
json_encodeEncode data as JSONjson_encode(data, options)$json = json_encode(["name" => "John", "age" => 30]);
json_decodeDecode JSON datajson_decode(json_string, assoc)$data = json_decode('{"name":"John","age":30}', true);
filter_varFilter a variablefilter_var(variable, filter, options)$email = "john@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { ... }
is_numericCheck if a value is numericis_numeric(value)$result = is_numeric("42");
strrevReverse a stringstrrev(string)echo strrev("Hello, PHP!");
absGet absolute valueabs(number)$absolute = abs(-5.5);
roundRound a numberround(number, precision, mode)$rounded = round(3.14159, 2);
trimRemove whitespacetrim(string, characters)$trimmed = trim(" Hello, PHP! ");
is_arrayCheck if a variable is an arrayis_array(variable)$isArray = is_array([1, 2, 3]);
array_keysGet array keysarray_keys(array, search_value, strict)$keys = array_keys(["name" => "John", "age" => 30]);

26-50

FunctionPurposeSyntaxExample
array_valuesGet all the values of an arrayarray_values(array)$values = array_values(["a" => "apple", "b" => "banana"]);
array_reverseReverse the order of an arrayarray_reverse(array, preserve_keys)$reversed = array_reverse([1, 2, 3]);
array_filterFilter elements of an arrayarray_filter(array, callback)$filtered = array_filter([1, 2, 3, 0, 4], fn($value) => $value > 2);
array_mapApply a callback to all elementsarray_map(callback, array)$squared = array_map(fn($value) => $value ** 2, [1, 2, 3]);
array_reduceReduce an array to a single valuearray_reduce(array, callback, initial)$sum = array_reduce([1, 2, 3], fn($carry, $item) => $carry + $item, 0);
array_searchSearch for a value in an arrayarray_search(needle, haystack, strict)$key = array_search("banana", ["a" => "apple", "b" => "banana"]);
array_key_existsCheck if a key exists in an arrayarray_key_exists(key, array)$exists = array_key_exists("name", ["age" => 30, "name" => "John"]);
array_uniqueRemove duplicate values from an arrayarray_unique(array, sort_flags)$unique = array_unique([1, 2, 2, 3, 3]);
is_stringCheck if a variable is a stringis_string(variable)$isString = is_string("Hello, PHP!");
is_intCheck if a variable is an integeris_int(variable)$isInt = is_int(42);
is_floatCheck if a variable is a floatis_float(variable)$isFloat = is_float(3.14);
is_boolCheck if a variable is a booleanis_bool(variable)$isBool = is_bool(true);
is_nullCheck if a variable is nullis_null(variable)$isNull = is_null(null);
is_callableCheck if a value is callableis_callable(value, syntax_only, callable_name)$isCallable = is_callable("myFunction");
definedCheck if a constant is defineddefined(constant_name)if (defined("MY_CONSTANT")) { ... }
defineDefine a constantdefine(name, value, case_insensitive)define("PI", 3.14159);
constantGet the value of a constantconstant(name)$pi = constant("PI");
file_existsCheck if a file or directory existsfile_exists(filename)$exists = file_exists("file.txt");
is_fileCheck if a path is a regular fileis_file(filename)$isFile = is_file("file.txt");
is_dirCheck if a path is a directoryis_dir(filename)$isDir = is_dir("directory/");
filemtimeGet the last modified time of a filefilemtime(filename)$timestamp = filemtime("file.txt");
file_get_contentsRead a file into a stringfile_get_contents(filename)$content = file_get_contents("file.txt");
file_put_contentsWrite a string to a filefile_put_contents(filename, data)file_put_contents("file.txt", "Hello, PHP!");
unlinkDelete a fileunlink(filename)unlink("file.txt");
mkdirCreate a directorymkdir(dirname, mode, recursive, context)mkdir("new_directory");
rmdirRemove a directoryrmdir(dirname, context)

51-75

FunctionPurposeSyntaxExample
countCount all elements in an arraycount(array, mode)$count = count([1, 2, 3]);
strlenGet the length of a stringstrlen(string)$length = strlen("Hello, PHP!");
str_replaceReplace occurrences in a stringstr_replace(search, replace, subject)$newString = str_replace("world", "PHP", "Hello, world!");
substrReturn part of a stringsubstr(string, start, length)$substring = substr("Hello, PHP!", 0, 5);
trimRemove whitespace from the beginning and end of a stringtrim(string, characters)$trimmed = trim(" Hello, PHP! ");
explodeSplit a string by a delimiterexplode(delimiter, string, limit)$parts = explode(",", "apple,banana,orange");
implodeJoin array elements into a stringimplode(glue, pieces)$fruitList = implode(", ", ["apple", "banana", "orange"]);
strtoupperConvert a string to uppercasestrtoupper(string)$uppercase = strtoupper("Hello, PHP!");
strtolowerConvert a string to lowercasestrtolower(string)$lowercase = strtolower("Hello, PHP!");
ucfirstUppercase the first character of a stringucfirst(string)$capitalized = ucfirst("hello, PHP!");
ucwordsUppercase the first character of each word in a stringucwords(string)$titleCase = ucwords("hello world");
randGenerate a random integerrand(min, max)$randomNumber = rand(1, 100);
dateFormat the date and timedate(format, timestamp)$currentDate = date("Y-m-d H:i:s");
timeGet the current Unix timestamptime()$timestamp = time();
strtotimeParse a date and time stringstrtotime(time, now)$timestamp = strtotime("2023-09-30 15:30:00");
json_encodeEncode a value as JSONjson_encode(value, options)$json = json_encode(["name" => "John", "age" => 30]);
json_decodeDecode a JSON string into a PHP valuejson_decode(json, assoc, depth)$data = json_decode('{"name":"John","age":30}', true);
file_existsCheck if a file or directory existsfile_exists(filename)$exists = file_exists("file.txt");
is_fileCheck if a path is a regular fileis_file(filename)$isFile = is_file("file.txt");
is_dirCheck if a path is a directoryis_dir(filename)$isDir = is_dir("directory/");
filemtimeGet the last modified time of a filefilemtime(filename)$timestamp = filemtime("file.txt");
file_get_contentsRead a file into a stringfile_get_contents(filename)$content = file_get_contents("file.txt");
file_put_contentsWrite a string to a filefile_put_contents(filename, data)file_put_contents("file.txt", "Hello, PHP!");
unlinkDelete a fileunlink(filename)unlink("file.txt");
mkdirCreate a directorymkdir(dirname, mode, recursive, context)mkdir("new_directory");
rmdirRemove a directoryrmdir(dirname, context)rmdir("directory/");

76-100

FunctionPurposeSyntaxExample
strrevReverse a stringstrrev(string)$reversed = strrev("Hello, PHP!");
strposFind the position of the first occurrence of a substring in a stringstrpos(haystack, needle, offset)$position = strpos("Hello, PHP!", "PHP");
strrposFind the position of the last occurrence of a substring in a stringstrrpos(haystack, needle, offset)$position = strrpos("Hello, PHP!", "PHP");
str_containsCheck if a string contains another substringstr_contains(haystack, needle)$contains = str_contains("Hello, PHP!", "PHP");
array_pushPush one or more elements onto the end of an arrayarray_push(array, value1, value2, ...)array_push($fruits, "banana", "orange");
array_popPop the element off the end of an arrayarray_pop(array)$lastElement = array_pop($fruits);
array_shiftShift an element off the beginning of an arrayarray_shift(array)$firstElement = array_shift($fruits);
array_unshiftPrepend one or more elements to the beginning of an arrayarray_unshift(array, value1, value2, ...)array_unshift($fruits, "banana", "orange");
array_mergeMerge one or more arraysarray_merge(array1, array2, ...)$mergedArray = array_merge($arr1, $arr2);
array_keysReturn all the keys of an arrayarray_keys(array, search_value, strict)$keys = array_keys($fruits, "apple");
array_valuesReturn all the values of an arrayarray_values(array)$values = array_values($fruits);
array_reverseReverse the order of elements in an arrayarray_reverse(array, preserve_keys)$reversedArray = array_reverse($fruits);
array_sliceExtract a slice of the arrayarray_slice(array, offset, length, preserve_keys)$slice = array_slice($fruits, 1, 2);
array_spliceRemove a portion of the array and replace it with something elsearray_splice(array, start, length, replacement)array_splice($fruits, 1, 2, ["banana", "orange"]);
sortSort an arraysort(array, sort_flags)sort($numbers);
rsortSort an array in reverse orderrsort(array, sort_flags)rsort($numbers);
asortSort an array and maintain index associationasort(array, sort_flags)asort($fruits);
arsortSort an array in reverse order and maintain index associationarsort(array, sort_flags)arsort($fruits);
ksortSort an array by keysksort(array, sort_flags)ksort($fruits);
krsortSort an array by keys in reverse orderkrsort(array, sort_flags)krsort($fruits);
in_arrayCheck if a value exists in an arrayin_array(needle, haystack, strict)$exists = in_array("apple", $fruits);
array_searchSearch for a value in an array and return its keyarray_search(needle, haystack, strict)$key = array_search("apple", $fruits);
array_fillFill an array with valuesarray_fill(start_index, num, value)$filledArray = array_fill(0, 3, "PHP");
rangeCreate an array containing a range of elementsrange(start, end, step)$numbers = range(1, 10, 2);