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;
- 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
Function | Purpose | Syntax | Example |
---|---|---|---|
echo | Output text | echo string, ... | echo "Hello, world!"; |
strlen | Get string length | strlen(string) | echo strlen("PHP is powerful"); |
str_replace | Replace part of a string | str_replace(search, replace, subject) | echo str_replace("world", "PHP", "Hello, world!"); |
substr | Get part of a string | substr(string, start, length) | echo substr("Hello, world!", 0, 5); |
implode / join | Join array elements | implode(glue, array) | echo implode(", ", ["apple", "banana", "cherry"]); |
explode | Split a string into an array | explode(delimiter, string) | $fruits = explode(", ", "apple, banana, cherry"); |
count | Count array elements | count(array, mode) | echo count([1, 2, 3]); |
array_push | Add elements to an array | array_push(array, value1, ...) | array_push($stack, "apple", "banana"); |
array_pop | Remove and return the last element of an array | array_pop(array) | $lastItem = array_pop($stack); |
array_merge | Merge arrays | array_merge(array1, array2, ...) | $merged = array_merge($arr1, $arr2); |
sort | Sort an array | sort(array, sort_flags) | sort($fruits); |
rand | Generate random number | rand(min, max) | $random = rand(1, 10); |
date | Format date and time | date(format, timestamp) | echo date("Y-m-d H:i:s"); |
time | Get current Unix timestamp | time() | $timestamp = time(); |
file_get_contents | Read a file into a string | file_get_contents(filename) | $content = file_get_contents("file.txt"); |
file_put_contents | Write a string to a file | file_put_contents(filename, data) | file_put_contents("file.txt", "Hello, PHP!"); |
json_encode | Encode data as JSON | json_encode(data, options) | $json = json_encode(["name" => "John", "age" => 30]); |
json_decode | Decode JSON data | json_decode(json_string, assoc) | $data = json_decode('{"name":"John","age":30}', true); |
filter_var | Filter a variable | filter_var(variable, filter, options) | $email = "john@example.com"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { ... } |
is_numeric | Check if a value is numeric | is_numeric(value) | $result = is_numeric("42"); |
strrev | Reverse a string | strrev(string) | echo strrev("Hello, PHP!"); |
abs | Get absolute value | abs(number) | $absolute = abs(-5.5); |
round | Round a number | round(number, precision, mode) | $rounded = round(3.14159, 2); |
trim | Remove whitespace | trim(string, characters) | $trimmed = trim(" Hello, PHP! "); |
is_array | Check if a variable is an array | is_array(variable) | $isArray = is_array([1, 2, 3]); |
array_keys | Get array keys | array_keys(array, search_value, strict) | $keys = array_keys(["name" => "John", "age" => 30]); |
26-50
Function | Purpose | Syntax | Example |
---|---|---|---|
array_values | Get all the values of an array | array_values(array) | $values = array_values(["a" => "apple", "b" => "banana"]); |
array_reverse | Reverse the order of an array | array_reverse(array, preserve_keys) | $reversed = array_reverse([1, 2, 3]); |
array_filter | Filter elements of an array | array_filter(array, callback) | $filtered = array_filter([1, 2, 3, 0, 4], fn($value) => $value > 2); |
array_map | Apply a callback to all elements | array_map(callback, array) | $squared = array_map(fn($value) => $value ** 2, [1, 2, 3]); |
array_reduce | Reduce an array to a single value | array_reduce(array, callback, initial) | $sum = array_reduce([1, 2, 3], fn($carry, $item) => $carry + $item, 0); |
array_search | Search for a value in an array | array_search(needle, haystack, strict) | $key = array_search("banana", ["a" => "apple", "b" => "banana"]); |
array_key_exists | Check if a key exists in an array | array_key_exists(key, array) | $exists = array_key_exists("name", ["age" => 30, "name" => "John"]); |
array_unique | Remove duplicate values from an array | array_unique(array, sort_flags) | $unique = array_unique([1, 2, 2, 3, 3]); |
is_string | Check if a variable is a string | is_string(variable) | $isString = is_string("Hello, PHP!"); |
is_int | Check if a variable is an integer | is_int(variable) | $isInt = is_int(42); |
is_float | Check if a variable is a float | is_float(variable) | $isFloat = is_float(3.14); |
is_bool | Check if a variable is a boolean | is_bool(variable) | $isBool = is_bool(true); |
is_null | Check if a variable is null | is_null(variable) | $isNull = is_null(null); |
is_callable | Check if a value is callable | is_callable(value, syntax_only, callable_name) | $isCallable = is_callable("myFunction"); |
defined | Check if a constant is defined | defined(constant_name) | if (defined("MY_CONSTANT")) { ... } |
define | Define a constant | define(name, value, case_insensitive) | define("PI", 3.14159); |
constant | Get the value of a constant | constant(name) | $pi = constant("PI"); |
file_exists | Check if a file or directory exists | file_exists(filename) | $exists = file_exists("file.txt"); |
is_file | Check if a path is a regular file | is_file(filename) | $isFile = is_file("file.txt"); |
is_dir | Check if a path is a directory | is_dir(filename) | $isDir = is_dir("directory/"); |
filemtime | Get the last modified time of a file | filemtime(filename) | $timestamp = filemtime("file.txt"); |
file_get_contents | Read a file into a string | file_get_contents(filename) | $content = file_get_contents("file.txt"); |
file_put_contents | Write a string to a file | file_put_contents(filename, data) | file_put_contents("file.txt", "Hello, PHP!"); |
unlink | Delete a file | unlink(filename) | unlink("file.txt"); |
mkdir | Create a directory | mkdir(dirname, mode, recursive, context) | mkdir("new_directory"); |
rmdir | Remove a directory | rmdir(dirname, context) |
51-75
Function | Purpose | Syntax | Example |
---|---|---|---|
count | Count all elements in an array | count(array, mode) | $count = count([1, 2, 3]); |
strlen | Get the length of a string | strlen(string) | $length = strlen("Hello, PHP!"); |
str_replace | Replace occurrences in a string | str_replace(search, replace, subject) | $newString = str_replace("world", "PHP", "Hello, world!"); |
substr | Return part of a string | substr(string, start, length) | $substring = substr("Hello, PHP!", 0, 5); |
trim | Remove whitespace from the beginning and end of a string | trim(string, characters) | $trimmed = trim(" Hello, PHP! "); |
explode | Split a string by a delimiter | explode(delimiter, string, limit) | $parts = explode(",", "apple,banana,orange"); |
implode | Join array elements into a string | implode(glue, pieces) | $fruitList = implode(", ", ["apple", "banana", "orange"]); |
strtoupper | Convert a string to uppercase | strtoupper(string) | $uppercase = strtoupper("Hello, PHP!"); |
strtolower | Convert a string to lowercase | strtolower(string) | $lowercase = strtolower("Hello, PHP!"); |
ucfirst | Uppercase the first character of a string | ucfirst(string) | $capitalized = ucfirst("hello, PHP!"); |
ucwords | Uppercase the first character of each word in a string | ucwords(string) | $titleCase = ucwords("hello world"); |
rand | Generate a random integer | rand(min, max) | $randomNumber = rand(1, 100); |
date | Format the date and time | date(format, timestamp) | $currentDate = date("Y-m-d H:i:s"); |
time | Get the current Unix timestamp | time() | $timestamp = time(); |
strtotime | Parse a date and time string | strtotime(time, now) | $timestamp = strtotime("2023-09-30 15:30:00"); |
json_encode | Encode a value as JSON | json_encode(value, options) | $json = json_encode(["name" => "John", "age" => 30]); |
json_decode | Decode a JSON string into a PHP value | json_decode(json, assoc, depth) | $data = json_decode('{"name":"John","age":30}', true); |
file_exists | Check if a file or directory exists | file_exists(filename) | $exists = file_exists("file.txt"); |
is_file | Check if a path is a regular file | is_file(filename) | $isFile = is_file("file.txt"); |
is_dir | Check if a path is a directory | is_dir(filename) | $isDir = is_dir("directory/"); |
filemtime | Get the last modified time of a file | filemtime(filename) | $timestamp = filemtime("file.txt"); |
file_get_contents | Read a file into a string | file_get_contents(filename) | $content = file_get_contents("file.txt"); |
file_put_contents | Write a string to a file | file_put_contents(filename, data) | file_put_contents("file.txt", "Hello, PHP!"); |
unlink | Delete a file | unlink(filename) | unlink("file.txt"); |
mkdir | Create a directory | mkdir(dirname, mode, recursive, context) | mkdir("new_directory"); |
rmdir | Remove a directory | rmdir(dirname, context) | rmdir("directory/"); |
76-100
Function | Purpose | Syntax | Example |
---|---|---|---|
strrev | Reverse a string | strrev(string) | $reversed = strrev("Hello, PHP!"); |
strpos | Find the position of the first occurrence of a substring in a string | strpos(haystack, needle, offset) | $position = strpos("Hello, PHP!", "PHP"); |
strrpos | Find the position of the last occurrence of a substring in a string | strrpos(haystack, needle, offset) | $position = strrpos("Hello, PHP!", "PHP"); |
str_contains | Check if a string contains another substring | str_contains(haystack, needle) | $contains = str_contains("Hello, PHP!", "PHP"); |
array_push | Push one or more elements onto the end of an array | array_push(array, value1, value2, ...) | array_push($fruits, "banana", "orange"); |
array_pop | Pop the element off the end of an array | array_pop(array) | $lastElement = array_pop($fruits); |
array_shift | Shift an element off the beginning of an array | array_shift(array) | $firstElement = array_shift($fruits); |
array_unshift | Prepend one or more elements to the beginning of an array | array_unshift(array, value1, value2, ...) | array_unshift($fruits, "banana", "orange"); |
array_merge | Merge one or more arrays | array_merge(array1, array2, ...) | $mergedArray = array_merge($arr1, $arr2); |
array_keys | Return all the keys of an array | array_keys(array, search_value, strict) | $keys = array_keys($fruits, "apple"); |
array_values | Return all the values of an array | array_values(array) | $values = array_values($fruits); |
array_reverse | Reverse the order of elements in an array | array_reverse(array, preserve_keys) | $reversedArray = array_reverse($fruits); |
array_slice | Extract a slice of the array | array_slice(array, offset, length, preserve_keys) | $slice = array_slice($fruits, 1, 2); |
array_splice | Remove a portion of the array and replace it with something else | array_splice(array, start, length, replacement) | array_splice($fruits, 1, 2, ["banana", "orange"]); |
sort | Sort an array | sort(array, sort_flags) | sort($numbers); |
rsort | Sort an array in reverse order | rsort(array, sort_flags) | rsort($numbers); |
asort | Sort an array and maintain index association | asort(array, sort_flags) | asort($fruits); |
arsort | Sort an array in reverse order and maintain index association | arsort(array, sort_flags) | arsort($fruits); |
ksort | Sort an array by keys | ksort(array, sort_flags) | ksort($fruits); |
krsort | Sort an array by keys in reverse order | krsort(array, sort_flags) | krsort($fruits); |
in_array | Check if a value exists in an array | in_array(needle, haystack, strict) | $exists = in_array("apple", $fruits); |
array_search | Search for a value in an array and return its key | array_search(needle, haystack, strict) | $key = array_search("apple", $fruits); |
array_fill | Fill an array with values | array_fill(start_index, num, value) | $filledArray = array_fill(0, 3, "PHP"); |
range | Create an array containing a range of elements | range(start, end, step) | $numbers = range(1, 10, 2); |
“ |