PHP Snippets & Tutorials
PHP snippets for string handling, arrays, dates, and common checks. Works on PHP 7.4+; PHP 8+ where noted.
Server-side logic often comes down to strings, arrays, and dates. The examples here are ready to use in scripts, WordPress snippets, or custom PHP apps. We note when a function requires PHP 8 (e.g. str_contains()) and give alternatives for older versions where it matters.
Check if a string contains a substring
$text = "I love to program!";
$word = "program";
$found = str_contains($text, $word); // true (PHP 8+)
On PHP 7.x use strpos($text, $word) !== false. str_contains() is available from PHP 8.0. For case-insensitive check use str_contains(strtolower($text), strtolower($word)).
Trim whitespace with trim()
$input = " hello world \n";
$trimmed = trim($input); // "hello world"
$left = ltrim($input); // "hello world \n"
$right = rtrim($input); // " hello world"
trim() removes spaces, tabs, and newlines from both ends. ltrim() and rtrim() strip only from the left or right. Pass a string as the second argument to remove custom characters.
Remove duplicates from an array
$items = ["a", "b", "a", "c", "b"];
$unique = array_unique($items); // keys preserved
$unique_list = array_values($unique); // reindex 0, 1, 2...
array_unique() keeps the first occurrence of each value and preserves keys. Use array_values() if you need a plain 0-based list. Works for strings and integers; for arrays as elements you need a custom approach.
Get the current month from a date
$date = new DateTime("2025-03-07");
$month = (int) $date->format("n"); // 3 (numeric)
$monthName = $date->format("F"); // "March"
format("n") gives 1–12, "F" gives the full month name. For the current date use new DateTime() with no arguments.
More PHP topics
See also: Code Snippets, Learn to Code.