Top 30 Trending PHP Coding Examples

To understand these PHP examples, you should know the following:

1. Write a PHP function to reverse a string

Code:

<?php
function reverseString(string $str): string {
    return strrev($str);
}

echo reverseString("PHP8");
?>

Output:

8PHP

Explanation: PHP provides a built-in strrev() function that reverses and returns the input string.

2. Check if a string is a palindrome in PHP

Code:

<?php
function isPalindrome(string $str): bool {
    $cleanStr = strtolower(preg_replace('/[^a-z0-9]/i', '',$str));
    return $cleanStr === strrev($cleanStr);
}

var_dump(isPalindrome("Never odd or even"));
?>

Output:

bool(true)

Explanation: Cleans the string using regular expressions, converts it to lowercase, and compares it against its reversed version using strict equality ===.

3. Solve the Two Sum problem using an associative array in PHP

Code:

<?php
function twoSum(array $nums, int $target): array {$map = [];
    foreach ($nums as$index => $num) {$diff = $target -$num;
        if (isset($map[$diff])) {
            return [$map[$diff],$index];
        }
        $map[$num] =$index;
    }
    return [];
}

print_r(twoSum([2, 7, 11, 15], 9));
?>

Output:

Array
(
    [0] => 0
    [1] => 1
)

Explanation: Stores seen numbers and their indices in an associative array hash table for linear O(n) lookup efficiency.

4. Use Constructor Property Promotion in modern PHP

Code:

<?php
class User {
    public function __construct(
        public string $name,
        public int $age = 18
    ) {}
}

$user = new User("Alice", 25);
echo "{$user->name} is {$user->age}";
?>

Output:

Alice is 25

Explanation: Constructor Property Promotion automatically combines property declarations and assignments inside __construct parameters.

5. Use Match Expressions in PHP as a replacement for switch

Code:

<?php
function getStatusMessage(int $code): string {
    return match ($code) {
        200, 201 => "Success",
        404 => "Not Found",
        500 => "Server Error",
        default => "Unknown Error",
    };
}

echo getStatusMessage(200);
?>

Output:

Success

Explanation: Match expressions perform strict equality comparisons (===), return values directly, and do not require break statements.

6. Safely navigate properties using the Nullsafe Operator in Java

Code:

<?php
class Address {
    public ?string $city = "New York";
}

class User {
    public ?Address $address = null;
}

$user = new User();
echo $user->address?->city ?? "No City Specified";
?>

Output:

No City Specified

Explanation: The nullsafe operator ?-> stops execution and yields null if any element in the chain resolves to null, preventing null reference errors.

7. Filter array elements using array_filter() and arrow functions in Java

Code:

<?php
$numbers = [1, 2, 3, 4, 5, 6];
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);

print_r(array_values($evens));
?>

Output:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

Explanation: array_filter evaluates elements against an arrow function fn($n) => $n % 2 === 0, returning matching values while array_values resets array indices.

8. Flatten a multi-dimensional nested array using array_merge and recursion in Java

Code:

<?php
function flattenArray(array $array): array {$result = [];
    foreach ($array as$item) {
        if (is_array($item)) {$result = array_merge($result, flattenArray($item));
        } else {
            $result[] =$item;
        }
    }
    return $result;
}

print_r(flattenArray([1, [2, [3, 4]], 5]));
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Explanation: Recursively checks each item with is_array(), merging inner nested elements into a unified flat result array.

9. Remove duplicates from an array using array_unique in PHP

Code:

<?php
$items = ["apple", "banana", "apple", "cherry", "banana"];
$unique = array_unique($items);

print_r(array_values($unique));
?>

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

Explanation: array_unique strips duplicate values from arrays, preserving the first key encountered.

10. Use Readonly Classes in modern PHP

Code:

<?php
readonly class Configuration {
    public function __construct(
        public string $environment,
        public bool $debug
    ) {}
}

$config = new Configuration("production", false);
echo $config->environment;
?>

Output:

production

Explanation: Declaring a class as readonly implicitly marks all of its properties as readonly, preventing modifications after initialization.

11. Enforce strict parameter types using Union Types and Intersection Types in PHP

Code:

<?php
function processInput(int|float $number): string {
    return "Processed: " . ($number * 2);
}

echo processInput(10.5);
?>

Output:

Processed: 21

Explanation: Union types (int|float) allow function parameters to accept multiple valid type declarations explicitly.

12. Generate sequences efficiently using PHP Generators and yield in PHP

Code:

<?php
function getRange(int $start, int$end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (getRange(1, 3) as $number) {
    echo "$number ";
}
?>

Output:

1 2 3

Explanation: Generators yield values lazily one at a time, conserving memory when dealing with large datasets.

13. Format dates using the DateTimeImmutable class in PHP

Code:

<?php
$date = new DateTimeImmutable("2026-09-17");
$nextWeek =$date->modify("+7 days");

echo $nextWeek->format("Y-m-d");
?>

Output:

2026-09-24

Explanation: DateTimeImmutable creates unmodifiable date objects; modifications return newly instantiated objects instead of altering originals.

14. Sort an array of associative arrays by a specific key using usort in PHP

Code:

<?php
$users = [
    ["name" => "Alice", "age" => 30],
    ["name" => "Bob", "age" => 22],
    ["name" => "Charlie", "age" => 25]
];

usort($users, fn($a,$b) => $a['age'] <=> $b['age']);

print_r($users);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Bob
            [age] => 22
        )

    [1] => Array
        (
            [name] => Charlie
            [age] => 25
        )

    [2] => Array
        (
            [name] => Alice
            [age] => 30
        )

)

Explanation: usort applies custom comparison sorting using the spaceship operator (<=>) to evaluate order.

15. Parse JSON strings into associative arrays safely in PHP

Code:

<?php
$json = '{"name": "Developer", "role": "Backend"}';
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

echo $data['role'];
?>

Output:

Backend

Explanation: Setting the second argument of json_decode to true converts JSON objects into associative arrays, while JSON_THROW_ON_ERROR handles invalid payloads safely.

16. Define Enumerations (Enums) in modern PHP

Code:

<?php
enum Status: string {
    case PENDING = 'pending';
    case APPROVED = 'approved';
    case REJECTED = 'rejected';
}

echo Status::APPROVED->value;
?>

Output:

approved

Explanation: Backed Enums provide strongly-typed enumerations bound to string or integer values.

17. Unpack arrays using array spread operator (…) in PHP

Code:

<?php
$arr1 = [1, 2];
$arr2 = [3, 4];$merged = [...$arr1, ...$arr2, 5];

print_r($merged);
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Explanation: Array unpacking via … expands array elements inline within newly constructed arrays.

18. Hash passwords securely using password_hash and password_verify in PHP

Code:

<?php
$password = "secret123";
$hash = password_hash($password, PASSWORD_BCRYPT);

var_dump(password_verify("secret123", $hash));
?>

Output:

bool(true)

Explanation: password_hash generates strong one-way cryptographic hashes, while password_verify checks plaintext credentials against stored hashes safely.

19. Read file contents safely line by line in PHP

Code:

<?php
$content = "Line 1\nLine 2";
$lines = explode("\n", $content);

foreach ($lines as$line) {
    echo trim($line) . " ";
}
?>

Output:

Line 1 Line 2

Explanation: explode splits text input using delimiter boundaries, and trim cleans whitespace or newline characters.

20. Extract regex pattern matches using preg_match_all in PHP

Code:

<?php
$text = "Contact info: test@example.com and admin@domain.org";
preg_match_all('/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i', $text,$matches);

print_r($matches[0]);
?>

Output:

Array
(
    [0] => test@example.com
    [1] => admin@domain.org
)

Explanation: preg_match_all extracts all occurrences matching regular expressions across target input strings.

21. Perform HTTP Requests using cURL in PHP

Code:

<?php
$ch = curl_init("https://jsonplaceholder.typicode.com/todos/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data['title'];
?>

Output:

delectus aut autem

Explanation: Initializes cURL sessions, sets CURLOPT_RETURNTRANSFER to capture string output, executes requests, and decodes returned JSON responses.

22. Use Fibers for non-blocking concurrency control in PHP

Code:

<?php
$fiber = new Fiber(function (): void {$value = Fiber::suspend('Fiber Suspended');
    echo "Resumed with: $value";
});

$output =$fiber->start();
echo $output . " | ";
$fiber->resume('Fiber Data');
?>

Output:

Fiber Suspended | Resumed with: Fiber Data

Explanation: Fibers allow code blocks to pause execution via Fiber::suspend() and resume state via ->resume().

23. Sanitize input data using filter_var in PHP

Code:

<?php
$email = "john.doe(at)example.com";
$sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);$isValid = filter_var("john.doe@example.com", FILTER_VALIDATE_EMAIL);

var_dump((bool)$isValid);
?>

Output:

bool(true)

Explanation: filter_var sanitizes strings and validates format integrity against built-in filter flags like FILTER_VALIDATE_EMAIL.

24. Combine array keys and values using array_combine in PHP

Code:

<?php
$keys = ["id", "name"];
$values = [101, "Alex"];
$combined = array_combine($keys,$values);

print_r($combined);
?>

Output:

Array
(
    [id] => 101
    [name] => Alex
)

Explanation: array_combine creates associative arrays by using one array for keys and another for corresponding values.

25. Implement a Simple Trait for Code Reusability in PHP

Code:

<?php
trait Logger {
    public function log(string $msg): void {
        echo "Log: $msg";
    }
}

class Service {
    use Logger;
}

$service = new Service();$service->log("System ready");
?>

Output:

Log: System ready

Explanation: Traits allow reusable sets of methods to be included across multiple independent class hierarchies.

26. Use the Null Coalescing Assignment Operator (??=) in PHP

Code:

<?php
$user = [];$user['role'] ??= 'Guest';

echo $user['role'];
?>

Output:

Guest

Explanation: The null coalescing assignment operator ??= assigns values to targets only if the target is currently unset or null.

27. Count character frequencies in a string using count_chars in PHP

Code:

<?php
$str = "php";
$freq = array_count_values(str_split($str));

print_r($freq);
?>

Output:

Array
(
    [p] => 2
    [h] => 1
)

Explanation: Splits strings into individual character arrays and tallies value frequencies via array_count_values.

28. Implement Custom Exception Handling in PHP

Code:

<?php
class InvalidAgeException extends Exception {}

function validateAge(int $age): void {
    if ($age < 18) {
        throw new InvalidAgeException("Underage user.");
    }
}

try {
    validateAge(15);
} catch (InvalidAgeException $e) {
    echo "Caught exception: " . $e->getMessage();
}
?>

Output:

Caught exception: Underage user.

Explanation: Custom exception classes extend standard Exception objects to handle domain-specific execution errors cleanly.

29. Calculate sum reduction using array_reduce in PHP

Code:

<?php
$numbers = [10, 20, 30, 40];
$total = array_reduce($numbers, fn($carry,$item) => $carry +$item, 0);

echo "Total: $total";
?>

Output:

Total: 100

Explanation: Iterates over arrays to reduce elements into a single accumulated result value using a callback function.

30. Chunk an array into smaller sub-arrays using array_chunk in PHP

Code:

<?php
$items = [1, 2, 3, 4, 5];
$chunked = array_chunk($items, 2);

print_r($chunked);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
        )

)

Explanation: Splits array elements into multi-dimensional chunks of specified size bounds.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

Run PHP 8 program in XAMPP Server on localhost
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment