PHP

变量

<?php ... ?>PHP opening/closing tags
$var = "value";Variable (always $ prefix)
echo "text";Output to browser
print_r($var);Print readable info
var_dump($var);Detailed type + value
define("CONST", val);Define constant
const NAME = val;Class constant
isset($var)Check if set and not null
empty($var)Check if empty/falsy

数组

stringText type
int / floatNumber types
booltrue or false
arrayArray type
nullNo value
gettype($var)Get type name
(int) $varCast to integer
(string) $varCast to string
intval($str)Parse integer
is_array($var)Type check

字符串

"Hello $name"Double-quote interpolation
'literal string'No interpolation
strlen($s)String length
strpos($s, "sub")Find position
substr($s, start, len)Substring
str_replace(old, new, $s)Replace
explode(",", $s)Split to array
implode(",", $arr)Join array to string
trim($s)Remove whitespace
strtolower($s) / strtoupper()Case conversion

函数

$arr = [1, 2, 3];Indexed array
$arr = ["k" => "v"];Associative array
count($arr)Array length
array_push($arr, $val)Add to end
array_pop($arr)Remove from end
array_merge($a, $b)Merge arrays
array_map(fn, $arr)Transform each element
array_filter($arr, fn)Filter elements
in_array($val, $arr)Check if value exists
array_keys($arr)Get all keys
sort($arr) / asort($arr)Sort by value
foreach ($arr as $k => $v)Loop over array

数据库

function fn($a, $b) { }Define function
fn($a, $b = 5)Default parameter
function fn(int $a): stringType hints
fn(...$args)Variadic arguments
$fn = fn($x) => $x * 2;Arrow function
class MyClass { }Define class
new MyClass()Create instance
$this->propInstance property
public / private / protectedVisibility
extends / implementsInheritance / interface

Control Flow

if ($cond) { } else { }If-else
switch ($val) { case: }Switch statement
match ($val) { pat => result }Match expression (8.0+)
for ($i=0; $i<$n; $i++)For loop
foreach ($arr as $v)Foreach loop
while ($cond) { }While loop
$a ?? $bNull coalescing
$a ?. method()Nullsafe operator (8.0+)

Error Handling & I/O

try { } catch (Exception $e) { }Try-catch
throw new Exception(msg)Throw exception
finally { }Always executes
file_get_contents($path)Read file to string
file_put_contents($path, $d)Write string to file
json_encode($data)Convert to JSON
json_decode($json, true)Parse JSON to array
allprintabledoc.com