PHP 8 cheatsheet
PHP 8: Strings and arrays
8 common PHP 8 tasks.
Search in strings
Check the start, end or contents of a string.
str_contains($text, 'error');
str_starts_with($url, 'https://');
str_ends_with($file, '.php');
Insert variables in strings
Use double quotes or curly braces for expressions.
echo "Hello, {$user->name}! You have {$count} messages.";
Transform and filter arrays
Map and filter, then reindex the result.
$names = array_map(fn ($u) => $u['name'], $users);
$adults = array_values(array_filter($users, fn ($u) => $u['age'] >= 18));
Sort with a comparison
Sort an array by a field using the spaceship operator.
usort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
Check keys and values
Test whether a key or value exists.
array_key_exists('id', $row);
in_array('admin', $roles, true);
Encode and decode JSON
Convert to and from JSON, throwing exceptions on errors.
$json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
$data = json_decode($json, true, flags: JSON_THROW_ON_ERROR);