PHP Cheatsheet

Strings and Arrays

Use this PHP reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Strings

$name = 'Grace';
'a $name';       // literal
"a $name";       // interpolated
strlen($name);
strtolower($name);
strtoupper($name);
trim('  hi  ');
substr('cheatsheet', 0, 5);   // cheat
str_pad('7', 3, '0', STR_PAD_LEFT); // 007
str_repeat('-', 10);
str_contains('hello', 'ell');
str_starts_with('hello', 'he');
str_ends_with('hello', 'lo');
str_replace('cat', 'dog', $text);

Single quotes are mostly literal. Double quotes interpolate variables and escapes.

Formatting

sprintf('%s scored %d (%.2f%%)', $name, 92, 91.667);
sprintf('%05d', 42);            // 00042
number_format(1234567.891, 2);  // 1,234,567.89
printf("%s\n", $line);          // sprintf that echoes

Heredoc and Nowdoc

$html = <<<HTML
<p>Hello, $name.</p>
HTML;

$raw = <<<'SQL'
select * from users where name = :name
SQL;

Heredoc (<<<TAG) interpolates like double quotes. Nowdoc (<<<'TAG') is literal like single quotes. The closing tag may be indented, and that indentation is stripped from every line.

Splitting and Joining

$parts = explode(',', 'a,b,c');
$text = implode(', ', ['a', 'b', 'c']);
$tokens = preg_split('/\s+/', trim($input));

Use explode for a simple delimiter and preg_split for regex splitting.

Regex

preg_match('/^\d{4}-\d{2}$/', '2026-07', $m);        // 1 on match
preg_match('/(?<user>\w+)@(\w+)/', $email, $m);      // $m['user'], $m[2]
preg_match_all('/\d+/', 'a1 b22 c333', $m);          // $m[0] = ['1','22','333']
preg_replace('/\s+/', ' ', $text);
preg_replace_callback('/\d+/', fn($m) => $m[0] * 2, $text);
preg_quote($userInput, '/');

Patterns are strings with delimiters (/.../) plus flags like i (case-insensitive), m (multiline), u (UTF-8). preg_match returns 1, 0, or false on pattern error, so compare with === 1.

Indexed Arrays

$names = ['Ada', 'Grace'];
$names[] = 'Maya';
$first = $names[0];
count($names);
array_slice($names, 0, 2);

Associative Arrays

$user = ['name' => 'Ada', 'role' => 'admin'];
$user['email'] = 'ada@example.com';
$role = $user['role'] ?? 'student';
array_key_exists('name', $user);
array_keys($user);
array_key_first($user);
array_key_last($user);

?? is the null coalescing operator. It is ideal for optional keys.

Destructuring, Merge, Spread

[$a, $b] = [1, 2];
['name' => $n, 'role' => $r] = $user;      // by key
foreach ($pairs as [$x, $y]) {}

$all = array_merge($defaults, $overrides);  // later keys win
$all = [...$defaults, ...$overrides];       // spread, string keys allowed
$combined = [...$listA, ...$listB, 99];

Array Helpers

array_map(fn($n) => $n * 2, $nums);
array_filter($nums, fn($n) => $n > 0);
array_values($filtered);               // reindex after filter
array_sum($nums);
array_unique($tags);
array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
in_array('Ada', $names, true);
array_search('Ada', $names, true);     // key or false
array_find($users, fn($u) => $u['age'] > 30);  // PHP 8.4+

Pass true as the third argument to in_array for strict comparison.

Sorting

sort($nums);            // values, reindexes keys
rsort($nums);           // descending
asort($map);            // by value, keeps keys
ksort($map);            // by key
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
uasort($map, fn($a, $b) => $b <=> $a);  // custom, keeps keys

Sort functions mutate the array in place and return true.