PHP Cheat Sheet
Welcome to the PHP cheat sheet! Whether you're a beginner just starting your journey in PHP development or an experienced programmer looking for a quick reference guide, this cheat sheet has something for you.
PHP is one of the most popular server-side scripting languages, widely used for web development to create dynamic and interactive websites. With its vast array of functions, methods, and constructs, keeping track of all PHP features can be a daunting task.
That's where this PHP cheat sheet comes in handy. We've compiled essential syntax, functions, commands, and best practices into a concise and easy-to-reference guide. You'll find valuable snippets and insights here.
Keep this cheatsheet by your side as a quick reference while coding, and you'll find that navigating the world of PHP becomes a breeze. Happy coding!
Echo Statement
The echo
keyword in PHP is used to output one or more strings to the web browser. It's one of the most basic and commonly used constructs for displaying text or variables to the user.
echo "Hello, World!"; // Outputs: Hello, World!
Comments
Comments in PHP are used to add explanatory notes to the code or to prevent the execution of code without deleting it. They are ignored by the PHP interpreter and have no impact on the program execution.
Syntax | Description |
---|---|
// | Single-line comment |
# | Alternative single-line comment |
/* ... */ | Multi-line or block comment |
// This is a single-line comment
# This is also a single-line comment
/* This
is
a
multi-line
comment */
echo "Comments are ignored by PHP!"; // Outputs: Comments are ignored by PHP!
PHPDoc
PHPDoc is a documentation system for PHP used to generate API documentation from specially-formatted comments directly in the code. It allows developers to write descriptions, define parameters, return types, and more in a standard way, making the code more understandable and maintainable.
PHPDoc comments start with /**
and use specific tags like @param
, @return
, and others to describe different aspects of functions, classes, or methods.
/**
* Calculates the sum of two numbers.
*
* @param int $a The first number
* @param int $b The second number
* @return int The sum of $a and $b
*/
function add($a, $b) {
return $a + $b;
}
In this example, the PHPDoc block explains what the function does, describes the parameters and their types, and defines the return type. It provides valuable information for anyone reading the code and can be used to generate automated documentation.
Variables and Constants
Variables in PHP are used to store data, such as numbers or strings, and they can be changed during the execution of a script. Constants, on the other hand, store a value that cannot be changed once defined. While variables are prefixed with a $
symbol and can be reassigned, constants are defined using the define()
function or the const
keyword and remain fixed throughout the program.
Variables Examples:
$variable1 = "Hello"; // Using double quotes
$variable2 = 'World'; // Using single quotes
$variable3 = 42; // Storing an integer
$variable4 = 3.14; // Storing a floating-point number
Constants Examples:
define("CONSTANT1", "I'm a constant"); // Using the define function
const CONSTANT2 = "I'm also a constant"; // Using the const keyword
Variables are versatile and can be reassigned as needed, while constants provide a way to store values that should remain unchanged throughout the execution of your script.
Data Types
Type | Description |
---|---|
bool | Boolean type, representing either true or false |
int | Integer type, representing whole numbers |
float | Floating-point number, representing numbers with decimal points |
string | String type, representing sequences of characters |
null | Null type, representing a variable with no value |
array | Array type, representing a collection of values |
object | Object type, representing instances of classes |
resource | Resource type, used to hold references to external resources |
void | Indicates a function that does not return a value |
never | Indicates a function that never returns (e.g., throws an exception) |
callable | Represents anything that can be called as a function |
iterable | Can be used as a collection, like arrays or objects implementing the Traversable interface |
mixed | Represents any type, including types not listed here |
Union Types
Union types in PHP allow a function parameter, property, or return value to be one of several types, giving more flexibility in type declarations. Introduced in PHP 8.0, union types use a vertical bar (|
) to separate each type that is allowed.
function combine(mixed $value1, int|string $value2): int|float {
return $value1 + $value2;
}
In this example, the $value2
parameter accepts either an integer or a string, and the function can return either an integer or a floating-point number, illustrating the use of union types.
Variable Scope
Variable scope refers to the context in which a variable is defined and where it can be accessed or modified. There are mainly two types of variable scope in PHP: local scope and global scope.
- Local Scope: A variable declared within a function has a local scope, meaning it can only be accessed within that function.
- Global Scope: A variable declared outside of a function has a global scope, meaning it can be accessed outside of functions but not inside unless it is explicitly defined as global within the function.
$globalVar = "I'm global"; // Global variable
function testLocalScope() {
$localVar = "I'm local"; // Local variable
global $globalVar; // Accessing global variable inside the function
echo $globalVar; // Outputs: I'm global
echo $localVar; // Outputs: I'm local
}
testLocalScope();
echo $globalVar; // Outputs: I'm global
echo $localVar; // Causes an error, as $localVar is not defined in this scope
Superglobal Variables
Superglobal variables in PHP are built-in arrays that are available in all scopes, meaning they can be accessed from anywhere in a script without needing to declare them as global. They provide access to various types of data, such as input data from forms, server information, session data, and more.
Superglobal | Description |
---|---|
$_GET | An associative array of variables passed via the URL query |
$_POST | An associative array of variables passed via HTTP POST |
$_REQUEST | An associative array merging $_GET , $_POST , and $_COOKIE |
$_SESSION | An associative array containing session variables |
$_COOKIE | An associative array of variables passed via HTTP cookies |
$_FILES | An associative array of items uploaded via HTTP POST |
$_SERVER | An array containing information such as headers, paths, and script locations |
$_ENV | An associative array of environment variables |
$_GLOBALS | An associative array containing all global variables |
Predefined Constants
Predefined constants in PHP are built-in constants that are always available, providing commonly needed values and information. These constants can represent anything from mathematical values, such as file paths, function names, and more. They can be particularly useful for debugging and logging purposes.
Constant | Description |
---|---|
__LINE__ | Represents the current line number in the file |
__FILE__ | Provides the full path and filename of the current file |
__DIR__ | Returns the directory path of the current file |
__FUNCTION__ | Contains the name of the current function |
__CLASS__ | Holds the class name, including the namespace it's in |
__TRAIT__ | Contains the trait name, including its namespace |
__METHOD__ | Specifies the current class method name |
__NAMESPACE__ | Represents the name of the current namespace |
Language Constructs
Language constructs are special expressions that look like functions but behave differently. They perform fundamental actions within the language, like outputting data, controlling structure, and managing variables.
Construct | Description |
---|---|
echo $string | Outputs one or more strings |
print $string | Outputs a string and returns the value 1 |
unset($var) | Destroys the specified variable or variables |
isset($var) | Checks if a variable is set and not null |
empty($var) | Checks if a variable is empty |
die() | Outputs a message and terminates the script execution |
exit() | Outputs a message and terminates the script execution |
include "file.php" | Includes and evaluates a file or warns if it fails |
require "file.php" | Includes and evaluates a file or errors if it fails |
include_once "file.php" | Includes and evaluates a file once or warns if it fails |
require_once "file.php" | Includes and evaluates a file once, or errors if it fails |
Arithmetic Operators
Operator | Description | Example |
---|---|---|
+ | Addition | $result = $a + $b |
- | Subtraction | $result = $a - $b |
* | Multiplication | $result = $a * $b |
/ | Division | $result = $a / $b |
% | Modulus | $result = $a % $b |
** | Exponentiation | $result = $a ** $b |
Assignment Operators
Operator | Description | Example | Equivalent |
---|---|---|---|
= | Assignment | $a = 5 | $a = 5 |
+= | Add and assign | $a += 3 | $a = $a + 3 |
-= | Subtract and assign | $a -= 2 | $a = $a - 2 |
*= | Multiply and assign | $a *= 4 | $a = $a * 4 |
/= | Divide and assign | $a /= 2 | $a = $a / 2 |
%= | Modulus and assign | $a %= 3 | $a = $a % 3 |
**= | Exponent and assign | $a **= 2 | $a = $a ** 2 |
&= | Bitwise and and assign | $a &= $b | $a = $a & $b |
|= | Bitwise or and assign | $a |= $b | $a = $a | $b |
^= | Bitwise xor and assign | $a ^= $b | $a = $a ^ $b |
<<= | Bitwise shift left and assign | $a <<= 2 | $a = $a << 2 |
>>= | Bitwise shift right and assign | $a >>= 2 | $a = $a >> 2 |
Comparison Operators
Operator | Description | Example |
---|---|---|
== | Equal (compares values, not types) | $a == $b |
=== | Identical (compares values and types) | $a === $b |
!= | Not equal | $a != $b |
<> | Not equal | $a <> $b |
!== | Not identical | $a !== $b |
< | Less than | $a < $b |
> | Greater than | $a > $b |
<= | Less than or equal to | $a <= $b |
>= | Greater than or equal to | $a >= $b |
<=> | Comparison (returns -1 , 0 , or 1 for < , = , > respectively) | $result = $a <=> $b |
Logical Operators
Operator | Description | Example |
---|---|---|
and | AND | $a and $b |
or | OR | $a or $b |
xor | Exclusive OR | $a xor $b |
! | NOT | !$a |
&& | AND | $a && $b |
|| | OR | $a || $b |
Bitwise Operators
These bitwise operators are used to perform operations on the binary representations of numbers. They allow you to manipulate individual bits in a value, which can be useful for low-level programming tasks and specific algorithmic needs.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | $a & $b |
| | Bitwise OR | $a | $b |
^ | Bitwise XOR | $a ^ $b |
~ | Bitwise NOT | ~$a |
<< | Bitwise Shift Left | $a << 2 |
>> | Bitwise Shift Right | $a >> 2 |
Error Control Operator
The error control operator is represented by the @
symbol and is used to suppress error messages that might be generated by an expression. By prefixing an expression with this operator, any errors or warnings that would typically be displayed are ignored, allowing the script to continue executing.
$result = @file_get_contents('nonexistentfile.txt');
In this example, if the file does not exist, no error message or warning will be displayed, and the $result
variable will simply be set to false
.
Increment/Decrement Operators
Operator | Description |
---|---|
++$a | Increments the variable $a before returning its value |
$a++ | Returns the current value of $a , then increments it |
--$a | Decrements the variable $a before returning its value |
$a-- | Returns the current value of $a , then decrements it |
String Operators
Operator | Description | Example |
---|---|---|
. | Concatenates two strings together | $str1 . $str2 |
.= | Concatenates and assigns to a variable | $str1 .= $str2 |
Functions
Functions are reusable blocks of code that perform specific tasks and can be called by name from anywhere in the script. They can take parameters (input values) and return values, allowing for more modular and maintainable code. Functions help in organizing the code, making it easier to read and reducing repetition.
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3); // $result will be 8
This add()
function takes two parameters, $a
and $b
, and returns their sum. It can be called as many times as needed with different arguments.
Named Arguments
Named arguments in PHP allow you to pass values to a function by specifying the names of the parameters you want to set rather than their order. This can make the code more readable and self-documenting, especially in functions that take a large number of parameters or have optional parameters with default values. Named arguments were introduced in PHP 8.0, allowing for more flexible function calls.
function drawRectangle($width, $height, $color = 'black') {
// Code to draw a rectangle
}
// Calling the function with named arguments
drawRectangle(width: 100, height: 200, color: 'red');
In this example, the arguments are passed to the drawRectangle()
function using the names of the parameters (width
, height
, and color
) rather than their order. This makes the function call more self-explanatory.
Anonymous Functions
Anonymous functions, also known as closures, are functions without a name. Unlike named functions, anonymous functions are usually not defined in the global scope but are instead stored in a variable or passed as an argument to other functions. They can be used as a value that can be assigned to variables, passed as arguments, or returned from other functions.
$add = function($a, $b) {
return $a + $b;
};
$result = $add(5, 3); // $result will be 8
In this example, the anonymous function takes two parameters and returns their sum. The function is assigned to the variable $add
, which can then be used, like the name of a regular function, to call the anonymous function. Anonymous functions are often used in callbacks and functional programming constructs.
Arrow Functions
Arrow functions were introduced in PHP 7.4 and provided a more concise syntax for writing anonymous functions for expressions that return a value. The key difference between arrow functions and regular anonymous functions is that arrow functions have a shorter syntax and automatically capture variables from the surrounding scope.
$multiplier = 2;
$multiply = fn($value) => $value * $multiplier;
$result = $multiply(5); // $result will be 10
In this example, the $multiplier
variable is automatically captured from the surrounding scope, and the arrow function $multiply
returns the product of $value
and $multiplier
.
Compared to a regular anonymous function, the arrow function is more concise.
$multiplier = 2;
$multiply = function($value) use ($multiplier) {
return $value * $multiplier;
};
The arrow function syntax is shorter and avoids the need for the use
keyword to import variables from the outer scope. It's useful for simple one-liners where a full anonymous function would be overkill.
Arrays
Arrays in PHP are a data structure that can hold multiple values under a single name, and they can be indexed or associative. There are three types of arrays.
- Indexed Array: Uses numeric indexes to access values.
- Associative Array: Uses named keys to access values.
- Multidimensional Array: Contains arrays within an array.
// Indexed Array
$colors = array("red", "green", "blue");
echo $colors[1]; // Outputs "green"
// Associative Array
$ages = array("John" => 25, "Mary" => 30);
echo $ages["John"]; // Outputs 25
// Multidimensional Array
$cars = array(
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2)
);
echo $cars[0][0]; // Outputs "Volvo"
You can declare an array using the shorter square bracket []
syntax. Starting with PHP 5.4, you can use the square bracket syntax, which is more concise.
$colors = ["red", "green", "blue"];
Destructuring Arrays
Destructuring arrays in PHP allows you to unpack values from an array into separate variables in a concise way. Introduced in PHP 7.1, it lets you list variables on the left-hand side of an assignment expression to extract corresponding values from the array on the right-hand side.
$array = [1, 2];
list($a, $b) = $array;
echo $a; // Outputs 1
echo $b; // Outputs 2
Here's the shorthand syntax:
$array = [1, 2];
[$a, $b] = $array;
echo $a; // Outputs 1
echo $b; // Outputs 2
Items can be skipped:
$array = [1, 2];
[, $b] = $array;
echo $b; // Outputs 2
Destructuring named keys allows you to unpack values from an associative array into separate variables by their keys:
$data = ['first' => 'John', 'last' => 'Doe'];
['first' => $first, 'last' => $last] = $data;
echo $first; // Outputs 'John'
echo $last; // Outputs 'Doe'
For Loop
A for
loop in PHP is used to execute a block of code a specified number of times, iterating over a sequence of values. It's defined with an initializer, a condition, and an increment expression, allowing concise control over the loop's behavior.
for ($i = 0; $i < 5; $i++) {
echo $i . " "; // Outputs "0 1 2 3 4"
}
In this example, the loop initializes $i
to 0
, continues as long as $i
is less than 5
, and increments $i
by 1
after each iteration, printing the values from 0 to 4.
Foreach Loop
A foreach
loop in PHP is used to iterate over the elements of an array or an object that implements the iterator interface. It provides an easy way to traverse arrays without the need to know the length or use an index.
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . " "; // Outputs "red green blue "
}
In this example, the foreach
loop iterates through the $colors
array, and the variable $color
takes on the value of each element in the array during the respective iteration.
While Loop
A while
loop in PHP executes a block of code as long as a specified condition is true. It's commonly used when the number of iterations is unknown beforehand, and the loop continues until the condition is no longer met.
$count = 0;
while ($count < 3) {
echo $count . " "; // Outputs "0 1 2 "
$count++;
}
In this example, the while
loop checks if $count
is less than 3
, and as long as this condition is true
, the code block inside the loop is executed, incrementing $count
by 1
in each iteration.
Do While Loop
A do-while
loop in PHP is similar to a regular while
loop, but it checks the condition after executing the block of code, ensuring that the code block is run at least once. Even if the condition is false
at the beginning, the loop body will be executed at least one time.
$count = 0;
do {
echo $count . " "; // Outputs "0 1 2 "
$count++;
} while ($count < 3);
In this example, the loop increments $count
and echoes it, repeating as long as $count
is less than 3
. Even if $count
started at 3 or higher, the code block would still run once.
If Statements
An if
statement in PHP is used to execute a block of code if a specified condition is true
. The else if
statement is used to add an additional condition to test if the initial if the condition is false
, and the else
statement is used to execute a block of code if none of the preceding conditions are true
.
$age = 18;
if ($age < 18) {
echo "You are a minor.";
} else if ($age == 18) {
echo "You are exactly 18 years old.";
} else {
echo "You are an adult.";
}
// Outputs "You are exactly 18 years old."
In this example, the if
statement first checks if $age
is less than 18. If this condition is false
, the else if
statement checks if $age
is exactly 18. If this condition is also false
, the code inside the else
block is executed.
Switch Statements
A switch
statement in PHP is used to compare a single expression against multiple possible values. It's a more concise way to write multiple if-else statements when checking the same variable or expression against different values. If a match is found, the corresponding code block is executed.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Tuesday":
echo "It's Tuesday!";
break;
case "Wednesday":
echo "Mid-week already!";
break;
case "Thursday":
echo "Almost Friday!";
break;
case "Friday":
echo "Weekend is here!";
break;
default:
echo "It's a weekend day!";
break;
}
// Outputs "Start of the work week!"
Rest and Spread Operators
The spread operator (...
) in PHP allows elements of an array or object to be expanded into individual arguments of a function call. It's useful when you want to pass an array of values as separate arguments to a function.
function add($a, $b, $c) {
return $a + $b + $c;
}
$values = [1, 2, 3];
echo add(...$values); // Outputs 6
In this example, the $values
array is spread into the add()
function's parameters, so $a
gets the value 1
, $b
gets 2
, and $c
gets 3
.
Alternatively, you can use the spread operator (...
) in a function definition to collect the remaining function arguments into an array. This is useful when you want to define a function that accepts any number of arguments.
function sum(...$numbers) { /* Some Logic */ }
echo sum(1, 2, 3, 4, 5); // Outputs 15
In this example, the sum()
function accepts any number of arguments and collects them into the $numbers
array.
Lastly, you can use the spread operator (...
) to merge arrays in PHP. It expands an array into individual elements, and you can use it inside another array to combine multiple arrays together.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];
$mergedArray = [...$array1, ...$array2, ...$array3];
print_r($mergedArray);
// Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6]
Classes
Classes in PHP are templates used to create objects which encapsulate properties and methods that are related to a specific entity or concept. They enable the principles of object-oriented programming, like inheritance, encapsulation, and polymorphism, allowing for a more organized and modular code structure. You can define a class with the class
keyword.
class Car {
}
New instances of a class can be created with the new
keyword.
$myCar = new Car();
Namespaces
Namespaces are a way to encapsulate items like classes, functions, and constants to prevent naming collisions, especially when working with external libraries or large codebases. They act like virtual directories, enabling you to group related code components together.
namespace MyProject\Utilities;
class Math {
}
You can use the class registered in a namespace by using the use
keyword.
// In another file or part of the code
use MyProject\Utilities\Math;
Access Modifiers (Visibility)
Access modifiers in PHP determine the accessibility of class properties, methods, and constants. These modifiers are crucial in object-oriented programming, helping to enforce encapsulation by controlling where class members can be accessed. There are three levels of access:
Keyword | Description | Example |
---|---|---|
public | Accessible from anywhere, including outside class | public function myFunction() { ... } |
protected | Accessible within the class and its child classes | protected $myVariable; |
private | Accessible only within the declaring class | private function privateFunction() { ... } |
Interfaces
Interfaces in PHP define abstract methods that classes implementing the interface must adhere to. They act as a contract, ensuring that the implementing class has specific methods with the same name, parameters, and return types as declared in the interface.
interface FooInterface {
public function Bar(): string;
}
Additional Class Keywords
Modifier | Description | Example |
---|---|---|
static | Allows methods/properties to be accessed directly on the class. | public static function example() { } |
abstract | Declares a method that must be implemented by any subclass. | abstract class Animal { abstract function sound(); } |
final | Prevents a method or class from being overridden by subclasses. | final public function example() { } |
readonly | A property that can only be set in the constructor. | public readonly $example; |
self | Refers to the current class, used to access static properties. | self::$example; |
parent | Refers to the parent class, used to call parent's methods. | parent::__construct(); |
static | Refers to the called class, used in late static binding. | static::example(); |
Magic Methods
Method | Description |
---|---|
__construct(...$args) | Called upon creating an object, allowing initialization. |
__destruct() | Called upon destroying an object, allowing cleanup. |
__toString() | Called when an object needs to be represented as a string. |
__invoke(...$args) | Allows an object to be called as a function. |
__get($name) | Triggered when reading data from an inaccessible (e.g., private ) property. |
__set($name, $value) | Triggered when writing data to an inaccessible (e.g., private ) property. |
__isset($name) | Triggered when using isset() or empty() on an inaccessible property. |
__unset($name) | Triggered when using unset() on an inaccessible property. |
__call($name, $args) | Called when invoking a method that does not exist or is not accessible within an object's context. |
__clone() | Triggered when an object is cloned, allowing custom behavior during cloning. |
Traits
Traits in PHP are a way to reuse methods across multiple classes. They allow you to create reusable code snippets that can be included in one or more classes. Unlike classes, traits can't be instantiated on their own. They're meant to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes.
trait SayHello {
public function hello() {
echo 'Hello, world!';
}
}
In the above example, the SayHello
trait defines a method hello()
.
We can use this tratit by using the use
keyword inside the MyClass
we can call that method on an instance of the class as if it were defined directly in the class.
class MyClass {
use SayHello;
}
$obj = new MyClass();
$obj->hello(); // Outputs: Hello, world!
Attributes
Attributes in PHP are a way to add meta-data to classes, properties, or methods, allowing you to define custom behavior or information about them. They are introduced in PHP 8, and you can use them to enhance or modify how elements within a class work.
#[Attribute]
class MyAttribute
{
}
In this example, MyAttribute
is an attribute because the #[Attribute]
was added above the class. Attributes can be applied to several elements, providing flexibility in adding meta-data to different parts of your code. Specifically, you can apply attributes to:
- Classes
- Properties
- Methods
- Function arguments
- Functions (including anonymous functions)
- Interfaces
- Traits
- Enum cases (as of PHP 8.1)
class MyClass
{
#[MyAttribute]
public $myProperty;
}
The custom attribute is applied to the property $myProperty
in the class MyClass
.
Enums
Enums in PHP are a way to define a set of named values, allowing you to use meaningful names instead of simple values, making your code more expressive and readable. Introduced in PHP 8.1, enums can represent a value as one of a predefined set of constants.
enum Status
{
case PENDING;
case APPROVED;
case REJECTED;
}
Cnum cases can contain integers, and enums can have methods as well. You can define an enum with integer values by specifying the type backing the enum.
enum Status: int
{
case PENDING = 1;
case APPROVED = 2;
case REJECTED = 3;
public function getColor(): string
{
return match($this)
{
Status::PENDING => 'yellow',
Status::APPROVED => 'green',
Status::REJECTED => 'red',
};
}
}
Match Statement
Match statements, introduced in PHP 8.0, provide a concise way to perform multiple comparisons using a switch-like expression, returning a value based on the first matched case. Unlike the switch
statement, the match expression does not require explicit break
statements, and it ensures a more strict comparison using the ===
operator.
$status = 2;
$result = match ($status) {
1 => 'pending',
2 => 'approved',
3 => 'rejected',
default => 'unknown',
};
echo $result; // Output: approved
Null Coalescing
The null coalescing operator (??
) in PHP is used to return the first non-null value in a list of expressions. It's particularly useful for providing a default value when you're not sure if a variable is set or is null
.
$username = $_GET['username'] ?? 'Guest';
// Equivalent to:
// $username = isset($_GET['username']) ? $_GET['username'] : 'Guest';
Nullsafe Operator
The nullsafe operator (?->
) in PHP, introduced in PHP 8.0, allows you to call methods or access properties on an object that might be null without causing an error. If the object is null
, the entire expression will evaluate to null
, letting you write more concise and safe code when working with potential null
objects.
$username = $user?->getUsername();
Constructor Property Promotion
Constructor property promotion in PHP, introduced in PHP 8.0, allows you to simplify the code by defining properties and assigning values to them directly in the constructor signature. This helps in reducing boilerplate code, as you don't need to manually declare properties or assign values within the constructor body. It's a more concise way to create classes when you need to both declare properties and initialize them with constructor arguments.
class User {
public function __construct(
public string $name,
private int $age,
protected string $email
) {
}
}
$user = new User('John', 25, 'john@example.com');
echo $user->name; // Output: John
Using new in Initializers
The new
keyword in PHP is used to create an instance of a class, and when used in conjunction with constructor property promotion, it allows for an efficient way to define and initialize class properties directly at the time of object creation. This feature became available in PHP 8.2
class Address {
public function __construct(public string $city, public string $state) {
}
}
class User {
public function __construct(
public string $name,
public Address $address = new Address('New York', 'NY')
) {
}
}
$user = new User('John');
echo $user->name; // Output: John
echo $user->address->city; // Output: New York
Readonly Properties
Readonly properties in PHP, introduced in PHP 8.1, allow you to declare properties that can be initialized only once and cannot be changed afterward. This ensures that the value of a readonly property remains constant after construction, providing an additional level of immutability within your classes.
class User {
public readonly string $username;
public function __construct(string $username) {
$this->username = $username;
}
}
Entire classes can be readonly only too. By setting a class to readonly, all properties are automatically readonly too.
readonly class User {
public string $username;
}
String Functions
Function | Description | Example |
---|---|---|
strlen($string) | Calculates the length of the given $string and returns it as an integer. | strlen('Hello') returns 5 . |
str_replace($search, $replace, $subject) | Searches for $search in $subject and replaces it with $replace . | str_replace('a', 'o', 'cat') returns 'cot' . |
strstr($haystack, $needle) | Finds the first occurrence of $needle in $haystack and returns the rest of the string. | strstr('hello', 'e') returns 'ello' . |
substr($string, $start, $length) | Returns a substring of $string starting at the $start position with the specified $length . | substr('apple', 1, 3) returns 'ppl' . |
strtolower($string) | Converts all characters in $string to lowercase letters. | strtolower('HELLO') returns 'hello' . |
strtoupper($string) | Converts all characters in $string to uppercase letters. | strtoupper('hello') returns 'HELLO' . |
trim($string) | Removes whitespace from both the beginning and end of $string . | trim(' hello ') returns 'hello' . |
ltrim($string) | Removes whitespace from the beginning (left side) of $string . | ltrim(' hello') returns 'hello' . |
rtrim($string) | Removes whitespace from the end (right side) of $string . | rtrim('hello ') returns 'hello' . |
explode($delimiter, $string) | Splits $string into an array based on the $delimiter . | explode(' ', 'hello world') returns ['hello', 'world'] . |
implode($glue, $array) | Joins elements of $array into a string, separated by $glue . | implode('-', [1, 2, 3]) returns '1-2-3' . |
str_repeat($string, $multiplier) | Repeats the $string $multiplier number of times, returning the concatenated result. | str_repeat('a', 3) returns 'aaa' . |
Math Functions
Function | Description | Example |
---|---|---|
abs($num) | Returns the absolute value of $num , which is the non-negative value without regard to its sign. | abs(-5) returns 5 . |
round($num) | Rounds $num to the nearest integer, using standard rounding rules. | round(4.6) returns 5 . |
ceil($num) | Rounds $num up to the next largest integer. | ceil(4.1) returns 5 . |
floor($num) | Rounds $num down to the next smallest integer. | floor(4.9) returns 4 . |
max($a, $b) | Returns the greater of $a and $b . If multiple parameters are provided, it returns the largest. | max(3, 5) returns 5 . |
min($a, $b) | Returns the lesser of $a and $b . If multiple parameters are provided, it returns the smallest. | min(3, 5) returns 3 . |
pow($a, $b) | Returns $a raised to the power of $b . | pow(2, 3) returns 8 . |
rand($min, $max) | Returns a random integer between $min and $max , inclusive. | rand(1, 10) could return any number between 1 and 10. |
sqrt($num) | Returns the square root of $num , which is the value that when multiplied by itself gives $num . | sqrt(9) returns 3 . |
Array Functions
Function | Description | Example |
---|---|---|
count($array) | Returns the number of elements in $array . | count([1, 2, 3]) returns 3 . |
sort($array) | Sorts the elements of $array in ascending order. | $arr = [3, 1, 2]; sort($arr); sorts $arr to [1, 2, 3] . |
array_merge($array1, $array2) | Merges the elements of $array1 and $array2 . | array_merge([1], [2]) returns [1, 2] . |
array_map($callback, $array) | Applies the $callback function to each element of $array . | array_map('strtoupper', ['a']) returns ['A'] . |
array_filter($array, $callback) | Returns an array containing elements of $array for which $callback returns true. | array_filter([1, 2], fn($n) => $n > 1) returns [2] . |
array_reduce($array, $callback, $initial) | Reduces $array to a single value using $callback starting with $initial value. | array_reduce([1, 2], fn($carry, $n) => $carry + $n, 0) returns 3 . |
array_slice($array, $offset, $length) | Returns part of $array starting at $offset and continuing for $length elements. | array_slice([1, 2, 3], 1, 1) returns [2] . |
array_keys($array) | Returns an array of keys from $array . | array_keys(['a' => 1]) returns ['a'] . |
array_values($array) | Returns an array of values from $array . | array_values(['a' => 1]) returns [1] . |
array_combine($keys, $values) | Returns an array of key/value pairs from $keys and $values . | array_combine(['a'], [1]) returns ['a' => 1] . |
array_reverse($array) | Returns a reversed copy of $array . | array_reverse([1, 2]) returns [2, 1] . |
array_search($needle, $haystack) | Returns the key of $needle in $haystack , or FALSE if not found. | array_search(2, [1, 2, 3]) returns 1 . |
array_unique($array) | Returns a copy of $array with duplicate values removed. | array_unique([1, 1, 2]) returns [1, 2] . |
array_diff($array1, $array2) | Returns elements of $array1 not in $array2 . | array_diff([1, 2], [2]) returns [1] . |
array_intersect($array1, $array2) | Returns elements of $array1 also in $array2 . | array_intersect([1, 2], [2, 3]) returns [2] . |
DateTime Class
The DateTime
class in PHP provides functions to work with date and time. It allows you to perform various operations like formatting, modifying, and calculating differences between dates and times.
$date = new DateTime('2023-08-12');
echo $date->format('Y-m-d H:i:s'); // Output: "2023-08-12 00:00:00"
Method | Description | Example |
---|---|---|
__construct(string $time = 'now') | Constructs a new DateTime object. | $date = new DateTime('2023-08-12'); |
format(string $format) | Returns a formatted date string. | $date->format('Y-m-d'); |
modify(string $modify) | Alters the timestamp by incrementing or decrementing in a format accepted by strtotime() . | $date->modify('+1 day'); |
setDate(int $year, int $month, int $day) | Sets the date. | $date->setDate(2023, 8, 12); |
setTime(int $hour, int $minute) | Sets the time. | $date->setTime(14, 55); |
add(DateInterval $interval) | Adds an amount of days, months, etc., to a DateTime object. | $date->add(new DateInterval('P1D')); |
sub(DateInterval $interval) | Subtracts an amount of days, months, etc., from a DateTime object. | $date->sub(new DateInterval('P1D')); |
diff(DateTime $datetime2) | Returns the difference between two DateTime objects. | $diff = $date1->diff($date2); |
getTimestamp() | Gets the Unix timestamp. | $timestamp = $date->getTimestamp(); |
setTimestamp(int $unixtimestamp) | Sets the date and time based on a Unix timestamp. | $date->setTimestamp(1691282400); |
File System Functions
Function | Description | Example |
---|---|---|
file_exists($filename) | Returns true if $filename exists; otherwise, returns false. | file_exists('file.txt') returns true if 'file.txt' exists. |
is_dir($filename) | Returns true if $filename is a directory; otherwise, returns false. | is_dir('dir/') returns true if 'dir/' is a directory. |
is_file($filename) | Returns true if $filename is a regular file; otherwise, returns false. | is_file('file.txt') returns true if 'file.txt' is a file. |
is_readable($filename) | Returns true if $filename is readable; otherwise, returns false. | is_readable('file.txt') checks if 'file.txt' is readable. |
is_writable($filename) | Returns true if $filename is writable; otherwise, returns false. | is_writable('file.txt') checks if 'file.txt' is writable. |
mkdir($pathname) | Creates a directory named $pathname . Returns true on success, false on failure. | mkdir('newdir') creates a directory named 'newdir'. |
rmdir($dirname) | Removes a directory named $dirname . Returns true on success, false on failure. | rmdir('olddir') removes a directory named 'olddir'. |
unlink($filename) | Removes a file named $filename . Returns true on success, false on failure. | unlink('file.txt') removes a file named 'file.txt'. |
file_get_contents($filename) | Returns the contents of $filename as a string, or FALSE on failure. | file_get_contents('file.txt') reads the contents of 'file.txt'. |
file_put_contents($filename, $data) | Writes $data to $filename . Returns the number of bytes written, or FALSE on failure. | file_put_contents('file.txt', 'Hello!') writes 'Hello!' to 'file.txt'. |