PHP Standard Library: Complete Overview
The PHP Standard Library (SPL) is a set of built-in classes, interfaces, and functions available in every PHP distribution without the need to install additional extensions. It covers key areas: string processing, arrays, file system, dates, regular expressions, as well as data structures and iterators. In this article, we will thoroughly examine the main components of the standard library with practical examples.
1. Functions for Working with Strings
PHP provides dozens of built-in functions for string manipulation. Let's look at the most commonly used ones:
strlen()— returns the length of a string.strpos()— finds the position of the first occurrence of a substring.substr()— extracts a portion of a string.str_replace()— replaces all occurrences of a substring.explode()andimplode()— split/join strings using a delimiter.
<?php$text = "Hello, world! Welcome to PHP.";echo strlen($text); // 35echo strpos($text, "world"); // 7echo substr($text, 0, 5); // "Hello"echo str_replace("world", "universe", $text); // "Hello, universe! Welcome to PHP."print_r(explode(" ", $text)); // Array ( [0] => Hello, [1] => world! [2] => Welcome [3] => to [4] => PHP. )?>2. Functions for Working with Arrays
Arrays are the foundation of PHP. The standard library includes powerful functions for processing them:
array_map()— applies a callback to each element.array_filter()— filters elements by condition.array_merge()— merges arrays.array_keys()andarray_values()— get keys/values.sort()andrsort()— sort an array.
<?php$numbers = [1, 2, 3, 4, 5, 6];// Double each element$doubled = array_map(fn($n) => $n * 2, $numbers);print_r($doubled); // [2, 4, 6, 8, 10, 12]
// Keep only even numbers$even = array_filter($numbers, fn($n) => $n % 2 === 0);print_r($even); // [1 => 2, 3 => 4, 5 => 6]
$merged = array_merge(['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4]);print_r($merged); // ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]?>3. Working with Files and the File System
PHP has functions for reading, writing, and managing files without external libraries:
fopen(),fwrite(),fread(),fclose()— low-level operations.file_get_contents()andfile_put_contents()— simple operations.file_exists(),is_dir(),mkdir()— checking and creating directories.scandir()— gets a list of files in a folder.
<?php// Writing to a file$data = "Hello, file!";file_put_contents('example.txt', $data);
// Reading from a file$content = file_get_contents('example.txt');echo $content; // Hello, file!
// Creating a directoryif (!file_exists('uploads')) { mkdir('uploads', 0755, true);}
// List of files$files = scandir('.');print_r($files);?>4. Working with Date and Time
The DateTime class and the date(), time() functions allow you to handle timestamps:
<?php// Current dateecho date('Y-m-d H:i:s'); // 2025-03-25 14:30:00
// Working with DateTime$date = new DateTime('2025-12-31');$date->modify('+1 month');echo $date->format('d.m.Y'); // 31.01.2026
// Difference between dates$now = new DateTime