Outsourced IT Partner
Support ยท systems ยท strategy
ยฉ 2026
One person, one business โ IT support here, websites at webology.online.
One person, one business โ IT support here, websites at webology.online.
๐ PHP Programming Language
Quick Reference & Cheat Sheet - Built-in Functions, Syntax & Standard Library
Basic Syntax
PHP Tags & Variables
Data Types
// Scalar types
$string = "Hello World";
$integer = 42;
$float = 3.14;
$boolean = true;
// Compound types
$array = array(1, 2, 3);
$array = [1, 2, 3]; // PHP 5.4+
$object = new stdClass();
// Special types
$null = null;
$resource = fopen("file.txt", "r");
// Type checking
var_dump($variable);
gettype($variable);
is_string($variable);
is_int($variable);
is_array($variable);
Operators
// Arithmetic
+ - * / % **
// Assignment
= += -= *= /= %= .=
// Comparison
== === != !== < > <= >= <=>
// Logical
&& || ! and or xor
// String
. (concatenation)
// Array
+ (union)
// Null coalescing (PHP 7+)
$username = $_GET['user'] ?? 'guest';
// Null coalescing assignment (PHP 7.4+)
$config['key'] ??= 'default_value';
Control Structures
Conditionals
// If statement
if ($condition) {
// code
} elseif ($another_condition) {
// code
} else {
// code
}
// Ternary operator
$result = $condition ? "true" : "false";
// Switch statement
switch ($variable) {
case 'value1':
// code
break;
case 'value2':
case 'value3':
// code for value2 or value3
break;
default:
// default code
}
Loops
// For loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
// While loop
while ($condition) {
// code
}
// Do-while loop
do {
// code
} while ($condition);
// Foreach loop
foreach ($array as $value) {
echo $value;
}
foreach ($array as $key => $value) {
echo "$key: $value";
}
// Break and continue
break; // exit loop
continue; // skip to next iteration
Functions
Function Definition
// Basic function
function greet($name) {
return "Hello, " . $name;
}
// Function with default parameters
function greet($name, $greeting = "Hello") {
return $greeting . ", " . $name;
}
// Function with type declarations (PHP 7+)
function add(int $a, int $b): int {
return $a + $b;
}
// Variable functions
$func_name = "greet";
echo $func_name("World"); // calls greet("World")
// Anonymous functions (closures)
$closure = function($name) {
return "Hello, " . $name;
};
// Arrow functions (PHP 7.4+)
$multiply = fn($x, $y) => $x * $y;
String Functions
String Manipulation
strlen($string)
substr($string, $start, $length)
strpos($haystack, $needle)
strrpos($haystack, $needle)
str_replace($search, $replace, $subject)
str_ireplace($search, $replace, $subject)
strtolower($string)
strtoupper($string)
ucfirst($string)
ucwords($string)
trim($string)
ltrim($string)
rtrim($string)
explode($delimiter, $string)
implode($glue, $array)
str_repeat($string, $multiplier)
str_pad($string, $length, $pad_string)
strcmp($str1, $str2)
strcasecmp($str1, $str2)
strrev($string)
Array Functions
Array Manipulation
count($array)
sizeof($array)
array_push($array, $value)
array_pop($array)
array_shift($array)
array_unshift($array, $value)
array_merge($array1, $array2)
array_slice($array, $offset, $length)
array_splice($array, $offset, $length)
array_reverse($array)
array_flip($array)
array_keys($array)
array_values($array)
array_search($needle, $haystack)
in_array($needle, $haystack)
array_key_exists($key, $array)
array_unique($array)
array_filter($array, $callback)
array_map($callback, $array)
array_reduce($array, $callback)
sort($array)
rsort($array)
asort($array)
arsort($array)
ksort($array)
krsort($array)
File System Functions
File Operations
fopen($filename, $mode)
fclose($handle)
fread($handle, $length)
fwrite($handle, $string)
fgets($handle)
fgetcsv($handle)
file_get_contents($filename)
file_put_contents($filename, $data)
file($filename)
readfile($filename)
copy($source, $dest)
rename($oldname, $newname)
unlink($filename)
file_exists($filename)
is_file($filename)
is_dir($filename)
is_readable($filename)
is_writable($filename)
filesize($filename)
filemtime($filename)
mkdir($pathname)
rmdir($dirname)
opendir($path)
readdir($handle)
scandir($directory)
glob($pattern)
Date & Time Functions
Date/Time Operations
date($format, $timestamp)
time()
mktime($hour, $minute, $second, $month, $day, $year)
strtotime($time)
gmdate($format, $timestamp)
gmmktime($hour, $minute, $second, $month, $day, $year)
microtime($get_as_float)
sleep($seconds)
usleep($micro_seconds)
DateTime Class (OOP)
// Create DateTime object
$date = new DateTime();
$date = new DateTime('2023-12-25');
$date = DateTime::createFromFormat('Y-m-d', '2023-12-25');
// Format date
echo $date->format('Y-m-d H:i:s');
// Modify date
$date->add(new DateInterval('P1D')); // Add 1 day
$date->sub(new DateInterval('P1M')); // Subtract 1 month
$date->modify('+1 week');
// Compare dates
$date1 = new DateTime('2023-01-01');
$date2 = new DateTime('2023-12-31');
$diff = $date1->diff($date2);
echo $diff->days; // Number of days difference
Math Functions
Mathematical Operations
abs($number)
ceil($value)
floor($value)
round($val, $precision)
max($values)
min($values)
rand($min, $max)
mt_rand($min, $max)
random_int($min, $max)
sqrt($arg)
pow($base, $exp)
exp($arg)
log($arg, $base)
sin($arg)
cos($arg)
tan($arg)
pi()
deg2rad($number)
rad2deg($number)
number_format($number, $decimals)
Classes & Objects
Class Definition
class Person {
// Properties
public $name;
private $age;
protected $email;
static $count = 0;
// Constants
const SPECIES = 'Homo sapiens';
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
self::$count++;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
// Static method
public static function getCount() {
return self::$count;
}
// Magic methods
public function __toString() {
return $this->name;
}
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
}
Inheritance & Interfaces
// Interface
interface Drawable {
public function draw();
}
// Abstract class
abstract class Shape {
abstract public function calculateArea();
public function getInfo() {
return "This is a shape";
}
}
// Inheritance
class Circle extends Shape implements Drawable {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
public function draw() {
echo "Drawing a circle";
}
}
// Traits
trait Logger {
public function log($message) {
echo "[LOG] " . $message;
}
}
class MyClass {
use Logger;
}
Error Handling
Exception Handling
// Try-catch block
try {
// Code that might throw an exception
throw new Exception("Something went wrong");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception
class CustomException extends Exception {
public function errorMessage() {
return "Custom error: " . $this->getMessage();
}
}
// Multiple catch blocks
try {
// risky code
} catch (InvalidArgumentException $e) {
// handle invalid argument
} catch (RuntimeException $e) {
// handle runtime error
} catch (Exception $e) {
// handle any other exception
}
Error Functions
error_reporting($level)
set_error_handler($callback)
trigger_error($message, $type)
error_get_last()
ini_set('display_errors', 1)
Superglobals
Global Variables
$_GET - URL parameters
$_POST - Form data
$_REQUEST - GET, POST, COOKIE
$_SESSION - Session variables
$_COOKIE - Cookie values
$_FILES - Uploaded files
$_SERVER - Server information
$_ENV - Environment variables
$GLOBALS - Global scope
Common $_SERVER Variables
$_SERVER['REQUEST_METHOD']
$_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST']
$_SERVER['SERVER_NAME']
$_SERVER['DOCUMENT_ROOT']
$_SERVER['SCRIPT_NAME']
$_SERVER['QUERY_STRING']
$_SERVER['HTTP_USER_AGENT']
$_SERVER['REMOTE_ADDR']
$_SERVER['HTTPS']