<?php ... ?> | PHP opening/closing tags |
<?= $var ?> | Short echo tag |
// comment | Single line comment |
/* multi-line */ | Multi-line comment |
echo "Hello"; | Output string |
print "Hello"; | Output (returns 1) |
var_dump($var); | Debug variable |
print_r($arr); | Print array readable |
$var = "value"; | Variable declaration |
$str = "Hello"; | String |
$int = 42; | Integer |
$float = 3.14; | Float |
$bool = true; | Boolean |
$arr = [1, 2, 3]; | Array |
$null = null; | Null |
define("CONST", "value"); | Define constant |
const CONST = "value"; | Class constant |
gettype($var) | Get type |
(int)$var, (string)$var | Type casting |
isset($var) | Check if set |
empty($var) | Check if empty |
is_null($var) | Check if null |
+ - * / % | Arithmetic operators |
** (power) | Exponentiation |
== != < > <= >= | Comparison operators |
=== !== | Identical (type + value) |
<=> (spaceship) | Combined comparison |
&& || ! | Logical operators |
?? | Null coalescing |
??= | Null coalescing assignment |
?: | Ternary operator |
. | String concatenation |
.= | Concatenation assignment |
strlen($str) | String length |
str_word_count($str) | Word count |
strrev($str) | Reverse string |
strpos($str, $find) | Find position |
str_replace($find, $replace, $str) | Replace string |
substr($str, $start, $length) | Substring |
strtoupper($str) | Uppercase |
strtolower($str) | Lowercase |
ucfirst($str) | Capitalize first |
ucwords($str) | Capitalize words |
trim($str) | Trim whitespace |
ltrim($str), rtrim($str) | Left/right trim |
explode(",", $str) | Split to array |
implode(",", $arr) | Join array |
sprintf("%s: %d", $s, $n) | Format string |
number_format($num, 2) | Format number |
"Hello $name" | Variable interpolation |
"Hello {$arr[0]}" | Complex interpolation |
'No $interpolation' | Single quotes (literal) |
<<<EOT
...
EOT; | Heredoc syntax |
<<<'EOT'
...
EOT; | Nowdoc syntax |
$arr = [1, 2, 3]; | Indexed array |
$arr = ["a" => 1, "b" => 2]; | Associative array |
array(1, 2, 3) | Array function |
range(1, 10) | Range array |
array_fill(0, 5, "x") | Fill array |
count($arr) | Array length |
array_push($arr, $val) | Push to end |
array_pop($arr) | Pop from end |
array_unshift($arr, $val) | Add to beginning |
array_shift($arr) | Remove from beginning |
array_merge($arr1, $arr2) | Merge arrays |
array_slice($arr, $start, $len) | Slice array |
array_splice($arr, $start, $len) | Remove/replace elements |
in_array($val, $arr) | Check if exists |
array_search($val, $arr) | Search for value |
array_keys($arr) | Get keys |
array_values($arr) | Get values |
array_flip($arr) | Swap keys/values |
array_reverse($arr) | Reverse array |
array_unique($arr) | Remove duplicates |
sort($arr), rsort($arr) | Sort array |
asort($arr), ksort($arr) | Sort by value/key |
usort($arr, $callback) | Custom sort |
array_map($fn, $arr) | Map function to array |
array_filter($arr, $fn) | Filter array |
array_reduce($arr, $fn, $init) | Reduce array |
array_walk($arr, $fn) | Apply function |
array_column($arr, "key") | Extract column |
if ($cond) { } | If statement |
if ($c) { } else { } | If-else |
if ($c) { } elseif ($c2) { } | Elseif |
$cond ? $true : $false | Ternary operator |
$val ?? $default | Null coalescing |
switch ($var) { case "a": break; } | Switch statement |
match ($var) { "a" => 1, default => 0 } | Match expression (PHP 8) |
for ($i = 0; $i < 10; $i++) { } | For loop |
foreach ($arr as $val) { } | Foreach loop |
foreach ($arr as $key => $val) { } | Foreach with key |
while ($cond) { } | While loop |
do { } while ($cond); | Do-while loop |
break; | Exit loop |
continue; | Skip iteration |
function name($arg) { return $val; } | Function definition |
function name($arg = "default") | Default parameter |
function name(string $arg): int | Type hints |
function name(?string $arg) | Nullable type |
function name(mixed $arg) | Mixed type (PHP 8) |
function name(&$arg) | Pass by reference |
function name(...$args) | Variadic function |
fn($x) => $x * 2 | Arrow function |
$fn = function($x) { return $x; }; | Anonymous function |
$fn = function($x) use ($y) { }; | Closure with use |
abs($num) | Absolute value |
round($num, $dec) | Round number |
ceil($num), floor($num) | Ceil/floor |
min($arr), max($arr) | Min/max value |
rand($min, $max) | Random number |
date("Y-m-d") | Format date |
time() | Current timestamp |
strtotime("next Monday") | Parse date string |
json_encode($arr) | Encode to JSON |
json_decode($json, true) | Decode JSON |
class MyClass { } | Class definition |
$obj = new MyClass(); | Create instance |
public $prop; | Public property |
private $prop; | Private property |
protected $prop; | Protected property |
readonly public $prop; | Readonly property (PHP 8.1) |
public function __construct() { } | Constructor |
public function __destruct() { } | Destructor |
$this->prop | Access instance property |
self::$prop | Access static property |
static::method() | Late static binding |
class Child extends Parent { } | Inheritance |
parent::__construct() | Call parent constructor |
interface MyInterface { } | Interface definition |
class C implements Interface { } | Implement interface |
abstract class A { } | Abstract class |
abstract public function m(); | Abstract method |
final class C { } | Final class |
trait MyTrait { } | Trait definition |
use MyTrait; | Use trait |
public function __construct(public $prop) | Constructor promotion |
#[Attribute] | Attributes |
str_contains($h, $n) | String contains |
str_starts_with($h, $n) | String starts with |
str_ends_with($h, $n) | String ends with |
enum Status: string { case A = "a"; } | Enumerations (PHP 8.1) |
$obj?->method() | Nullsafe operator |
MyClass::class | Class name constant |
$_GET["param"] | GET parameters |
$_POST["field"] | POST data |
$_REQUEST | GET + POST + COOKIE |
$_SERVER["REQUEST_METHOD"] | Server/request info |
$_SESSION["key"] | Session data |
$_COOKIE["name"] | Cookie data |
$_FILES["upload"] | Uploaded files |
$_ENV["VAR"] | Environment variables |
session_start(); | Start session |
$_SESSION["key"] = $val; | Set session value |
session_destroy(); | Destroy session |
setcookie("name", "value", time()+3600); | Set cookie |
setcookie("name", "", time()-3600); | Delete cookie |
header("Location: /page"); | Redirect |
header("Content-Type: application/json"); | Set content type |
http_response_code(404); | Set response code |
headers_sent() | Check if headers sent |
exit; / die("msg"); | Stop execution |
file_get_contents($path) | Read file contents |
file_put_contents($path, $data) | Write to file |
file_exists($path) | Check if file exists |
is_file($path), is_dir($path) | Check type |
fopen($path, "r") | Open file handle |
fread($handle, $length) | Read from handle |
fwrite($handle, $data) | Write to handle |
fclose($handle) | Close handle |
unlink($path) | Delete file |
copy($src, $dst) | Copy file |
rename($old, $new) | Rename/move file |
mkdir($path, 0755, true) | Create directory |
scandir($path) | List directory |
$pdo = new PDO($dsn, $user, $pass); | Connect to database |
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | Set error mode |
$stmt = $pdo->prepare($sql); | Prepare statement |
$stmt->execute([$val]); | Execute with params |
$stmt->bindParam(":name", $val); | Bind parameter |
$row = $stmt->fetch(PDO::FETCH_ASSOC); | Fetch one row |
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); | Fetch all rows |
$pdo->lastInsertId() | Last insert ID |
$pdo->beginTransaction(); | Begin transaction |
$pdo->commit(); $pdo->rollBack(); | Commit/rollback |
try { } catch (Exception $e) { } | Try-catch block |
catch (TypeError | ValueError $e) | Multiple exceptions |
finally { } | Finally block |
throw new Exception("msg"); | Throw exception |
$e->getMessage() | Get error message |
$e->getCode() | Get error code |
$e->getTrace() | Get stack trace |
class MyException extends Exception { } | Custom exception |
error_reporting(E_ALL); | Report all errors |
ini_set("display_errors", 1); | Display errors |
set_error_handler($callback); | Custom error handler |
set_exception_handler($callback); | Custom exception handler |
trigger_error("msg", E_USER_ERROR); | Trigger error |