Skip to content

Standard Library

Overview

PHP has a rich standard library that provides a large number of built-in functions and extensions to handle various common tasks. This chapter will introduce the most important standard library features, including string processing, array operations, date and time, mathematical functions, file system operations, and more.

String Functions

Basic String Operations

php
<?php
$text = "  Hello World  ";

// String length and basic operations
echo "Length: " . strlen($text) . "\n";
echo "UTF-8 length: " . mb_strlen("你好世界") . "\n";
echo "Uppercase: " . strtoupper($text) . "\n";
echo "Lowercase: " . strtolower($text) . "\n";
echo "Trimmed: '" . trim($text) . "'\n";

// String search and replace
$haystack = "The quick brown fox";
echo "Position: " . strpos($haystack, "quick") . "\n";
echo "Replace: " . str_replace("fox", "cat", $haystack) . "\n";

// String split and join
$fruits = explode(",", "apple,banana,orange");
$joined = implode(" | ", $fruits);
echo "Joined: $joined\n";

// Format string
$name = "Zhang San";
$age = 25;
$formatted = sprintf("Name: %s, Age: %d", $name, $age);
echo "Formatted: $formatted\n";
?>

Array Functions

Array Operations

php
<?php
// Array creation and basic operations
$numbers = [1, 2, 3, 4, 5];
$fruits = ["apple", "banana", "orange"];

echo "Array length: " . count($numbers) . "\n";

// Add and remove elements
array_push($fruits, "grape");
$last = array_pop($fruits);
echo "Removed element: $last\n";

// Array merge and slice
$merged = array_merge($numbers, [6, 7, 8]);
$slice = array_slice($numbers, 1, 3);
print_r($slice);

// Array search and filter
$students = [
    ['name' => 'Zhang San', 'score' => 85],
    ['name' => 'Li Si', 'score' => 92],
    ['name' => 'Wang Wu', 'score' => 78]
];

// Get specific column
$scores = array_column($students, 'score');
print_r($scores);

// Filter array
$excellent = array_filter($students, function($student) {
    return $student['score'] >= 90;
});
print_r($excellent);

// Array sorting
sort($numbers);
usort($students, function($a, $b) {
    return $b['score'] - $a['score'];
});
print_r($students);
?>

Date and Time Functions

Basic Date and Time Operations

php
<?php
// Current time
echo "Current timestamp: " . time() . "\n";
echo "Current date: " . date('Y-m-d H:i:s') . "\n";

// Format date
$timestamp = time();
echo "Year: " . date('Y', $timestamp) . "\n";
echo "Chinese format: " . date('Y年m月d日 H:i:s') . "\n";

// Relative time
echo "Tomorrow: " . date('Y-m-d', strtotime('+1 day')) . "\n";
echo "Next week: " . date('Y-m-d', strtotime('+1 week')) . "\n";

// DateTime class
$date1 = new DateTime();
$date2 = new DateTime('2024-01-15 10:30:00');

echo "Current time: " . $date1->format('Y-m-d H:i:s') . "\n";
echo "Specified time: " . $date2->format('Y-m-d H:i:s') . "\n";

// Date calculation
$date = new DateTime('2024-01-01');
$date->add(new DateInterval('P1M')); // Add 1 month
echo "After adding time: " . $date->format('Y-m-d') . "\n";

// Timezone handling
$utc = new DateTime('2024-01-15 12:00:00', new DateTimeZone('UTC'));
$shanghai = $utc->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo "Shanghai time: " . $shanghai->format('Y-m-d H:i:s T') . "\n";
?>

Mathematical Functions

Basic Mathematical Operations

php
<?php
// Basic functions
echo "Absolute value: " . abs(-5) . "\n";
echo "Maximum: " . max([1, 3, 2, 5, 4]) . "\n";
echo "Ceiling: " . ceil(3.14) . "\n";
echo "Round: " . round(3.14159, 2) . "\n";

// Power and square root
echo "Power: " . pow(2, 3) . "\n";
echo "Square root: " . sqrt(16) . "\n";

// Random numbers
echo "Random integer: " . mt_rand(1, 100) . "\n";
echo "Random decimal: " . mt_rand() / mt_getrandmax() . "\n";

// Base conversion
echo "Decimal to binary: " . decbin(255) . "\n";
echo "Decimal to hexadecimal: " . dechex(255) . "\n";

// Statistical functions
$scores = [85, 92, 78, 95, 88];
$sum = array_sum($scores);
$average = $sum / count($scores);
echo "Sum: $sum, Average: $average\n";
?>

File System Functions

File and Directory Operations

php
<?php
$filename = 'test.txt';
$directory = '.';

// File checks
echo "File exists: " . (file_exists($filename) ? "Yes" : "No") . "\n";
echo "Is file: " . (is_file($filename) ? "Yes" : "No") . "\n";
echo "Is directory: " . (is_dir($directory) ? "Yes" : "No") . "\n";

// File information
if (file_exists($filename)) {
    echo "File size: " . filesize($filename) . " bytes\n";
    echo "Modified time: " . date('Y-m-d H:i:s', filemtime($filename)) . "\n";
}

// Path information
$path = '/path/to/document.pdf';
echo "Directory name: " . dirname($path) . "\n";
echo "File name: " . basename($path) . "\n";
echo "Extension: " . pathinfo($path, PATHINFO_EXTENSION) . "\n";

// Directory traversal
$files = scandir('.');
echo "Current directory files:\n";
foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo "- $file\n";
    }
}

// Find files using glob
$phpFiles = glob('*.php');
echo "PHP file count: " . count($phpFiles) . "\n";
?>

JSON and Serialization

JSON Processing

php
<?php
// Array to JSON
$data = [
    'name' => 'Zhang San',
    'age' => 25,
    'hobbies' => ['Reading', 'Swimming', 'Programming']
];

$json = json_encode($data, JSON_UNESCAPED_UNICODE);
echo "JSON: $json\n";

// JSON to array
$decoded = json_decode($json, true);
print_r($decoded);

// Error handling
$invalidJson = '{"name": "Zhang San", "age":}';
$result = json_decode($invalidJson);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON error: " . json_last_error_msg() . "\n";
}

// Serialization
$serialized = serialize($data);
echo "Serialized: $serialized\n";

$unserialized = unserialize($serialized);
print_r($unserialized);
?>

Filter Functions

Data Validation and Filtering

php
<?php
// Validation filters
$email = 'user@example.com';
$url = 'https://www.example.com';
$int = '123';

echo "Email validation: " . (filter_var($email, FILTER_VALIDATE_EMAIL) ? 'Valid' : 'Invalid') . "\n";
echo "URL validation: " . (filter_var($url, FILTER_VALIDATE_URL) ? 'Valid' : 'Invalid') . "\n";
echo "Integer validation: " . (filter_var($int, FILTER_VALIDATE_INT) !== false ? 'Valid' : 'Invalid') . "\n";

// Sanitization filters
$string = '<script>alert("xss")</script>Hello!';
echo "Sanitized string: " . filter_var($string, FILTER_SANITIZE_STRING) . "\n";
echo "Sanitized email: " . filter_var('user@exa mple.com', FILTER_SANITIZE_EMAIL) . "\n";

// Batch filtering
$data = [
    'email' => 'user@example.com',
    'age' => '25',
    'name' => '<script>alert("xss")</script>Zhang San'
];

$filters = [
    'email' => FILTER_VALIDATE_EMAIL,
    'age' => FILTER_VALIDATE_INT,
    'name' => FILTER_SANITIZE_STRING
];

$result = filter_var_array($data, $filters);
print_r($result);
?>

Utility Functions

Common Utilities

php
<?php
// Generate unique ID and hash
echo "UUID: " . uniqid() . "\n";
echo "MD5: " . md5('password') . "\n";
echo "SHA256: " . hash('sha256', 'password') . "\n";

// Password hashing (secure)
$password = 'mypassword';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo "Secure hash: $hashedPassword\n";

if (password_verify($password, $hashedPassword)) {
    echo "Password verification successful\n";
}

// Encoding and decoding
$data = "Hello World";
echo "Base64 encoded: " . base64_encode($data) . "\n";
echo "URL encoded: " . urlencode($data) . "\n";

// Memory and performance
$startTime = microtime(true);
$startMemory = memory_get_usage();

// Execute operation
$sum = array_sum(range(1, 10000));

$endTime = microtime(true);
$endMemory = memory_get_usage();

echo "Execution time: " . ($endTime - $startTime) . " seconds\n";
echo "Memory usage: " . ($endMemory - $startMemory) . " bytes\n";

// System information
echo "PHP version: " . phpversion() . "\n";
echo "Operating system: " . php_uname('s') . "\n";
?>

Utility Class Examples

Utility Class

php
<?php
class Utils {
    // Format bytes
    public static function formatBytes($bytes, $precision = 2) {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes >= 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
    
    // Generate random string
    public static function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        
        return $randomString;
    }
    
    // Validate email
    public static function isValidEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
    
    // Clean HTML
    public static function cleanHtml($html) {
        return htmlspecialchars(strip_tags($html), ENT_QUOTES, 'UTF-8');
    }
    
    // Truncate text (supports Chinese)
    public static function truncate($text, $length, $suffix = '...') {
        if (mb_strlen($text, 'UTF-8') <= $length) {
            return $text;
        }
        
        return mb_substr($text, 0, $length, 'UTF-8') . $suffix;
    }
}

// Usage examples
echo "Format bytes: " . Utils::formatBytes(1048576) . "\n";
echo "Random string: " . Utils::generateRandomString(12) . "\n";
echo "Email validation: " . (Utils::isValidEmail('test@example.com') ? 'Valid' : 'Invalid') . "\n";
echo "Truncate text: " . Utils::truncate('这是一段很长的中文文本内容', 10) . "\n";
?>

Error Handling and Debugging

Debugging Functions

php
<?php
// Debug output
$data = [
    'user' => 'admin',
    'permissions' => ['read', 'write', 'delete']
];

echo "var_dump output:\n";
var_dump($data);

echo "\nprint_r output:\n";
print_r($data);

// Custom error handler
function customErrorHandler($severity, $message, $file, $line) {
    echo "Error: [$severity] $message in $file on line $line\n";
}

set_error_handler('customErrorHandler');

// Performance monitoring
class PerformanceMonitor {
    private $startTime;
    
    public function start() {
        $this->startTime = microtime(true);
    }
    
    public function end($operation = '') {
        $endTime = microtime(true);
        $duration = $endTime - $this->startTime;
        echo "$operation took: " . number_format($duration, 4) . " seconds\n";
        echo "Memory usage: " . number_format(memory_get_usage() / 1024 / 1024, 2) . " MB\n";
    }
}

$monitor = new PerformanceMonitor();
$monitor->start();

// Execute some operations
$sum = array_sum(range(1, 100000));

$monitor->end('Array sum');
?>

Best Practices

Usage Recommendations

  1. Prefer built-in functions: PHP built-in functions are usually faster and safer
  2. Pay attention to character encoding: Use mb_* functions when handling Chinese characters
  3. Validate user input: Use functions like filter_var to validate data
  4. Error handling: Always check function return values and possible errors
  5. Performance considerations: Avoid repeated function calls in loops

Security Considerations

  • Validate and filter all user input
  • Use appropriate data sanitization functions
  • Avoid information leakage (such as file paths, error messages)
  • Use secure password hashing methods

Summary

PHP standard library provides rich functionality:

  • String functions: Text processing and formatting
  • Array functions: Data manipulation and algorithm processing
  • Date and time: Time handling and calculation
  • Mathematical functions: Numerical calculation and statistics
  • File system: File and directory operations
  • Data processing: JSON, serialization, filtering
  • Utility functions: Encoding, hashing, debugging

Mastering these standard library functions can greatly improve development efficiency and code quality. In the next chapter, we will learn about PHP learning resources and advanced directions.

Content is for learning and research only.