PHP Functions & Modular Code

Key Takeaway: Practice PHP programming with 84+ practical code examples covering syntax, arrays, strings, functions, OOP, JSON, and file handling — all with expected terminal outputs.

Audience & Use Case: Designed for web developers, backend engineers, Laravel developers, computer science students, and interview candidates mastering modern PHP.

Last updated: September 2026 84 Verified Examples

Quick Start & How to Use

  1. Select a PHP program topic from the sidebar menu (or mobile dropdown).
  2. Examine the clear PHP code syntax and corresponding terminal output.
  3. Copy the code directly or run it live in our Online PHP Compiler.
  4. Experiment with arrays, functions, and OOP classes to solidify your server-side programming skills.

Who is this for: Web developers, Laravel learners, API engineers, and CS students.

Related Tools:PHP Compiler · PHP Official Manual · JavaScript Examples · Python Examples

How to use php serialize() and unserialize() Function

Run Online

Converts complex PHP data structures to storable string representations and back.

Program (PHP)
<?php

$userSession = [
    'user_id' => 42,
    'username' => 'alex_dev',
    'roles' => ['admin', 'developer']
];

$serialized = serialize($userSession);
echo "Serialized String:\n$serialized\n\n";

$unserialized = unserialize($serialized);
echo "Unserialized Array:\n";
print_r($unserialized);
?>
Expected Output
Serialized String:
a:3:{s:7:"user_id";i:42;s:8:"username";s:8:"alex_dev";s:5:"roles";a:2:{i:0;s:5:"admin";i:1;s:9:"developer";}}

Unserialized Array:
Array
(
    [user_id] => 42
    [username] => alex_dev
    [roles] => Array
        (
            [0] => admin
            [1] => developer
        )

)

PHP Foreach Loop Example

Run Online

Demonstrates iterating over associative arrays using key => value pairs.

Program (PHP)
<?php

$scores = [
    "Math" => 95,
    "Science" => 88,
    "English" => 92
];

echo "Subject Scores:\n";
foreach ($scores as $subject => $score) {
    echo "- $subject: $score\n";
}
?>
Expected Output
Subject Scores:
- Math: 95
- Science: 88
- English: 92

PHP Functions and Default Arguments

Run Online

Creates user-defined functions with type hints and default parameter values.

Program (PHP)
<?php

function greet(string $name, string $greeting = "Hello"): string {
    return "$greeting, $name!";
}

echo greet("Alice") . "\n";
echo greet("Bob", "Good morning") . "\n";
?>
Expected Output
Hello, Alice!
Good morning, Bob!

How to implement callback in PHP?

Run Online

Uses callable typehinting, call_user_func(), or anonymous functions as arguments.

Program (PHP)
<?php

function processItem($item, callable $callback) {
    return $callback($item);
}

$uppercase = function($str) {
    return strtoupper($str);
};

$result = processItem("hello php developers", $uppercase);
echo "Callback Output: $result\n";
?>
Expected Output
Callback Output: HELLO PHP DEVELOPERS

How to check foreach Loop Key Value in PHP?

Run Online

Iterates over associative arrays checking both keys and values in foreach loops.

Program (PHP)
<?php

$config = [
    'app_name' => 'OperateTools',
    'debug_mode' => true,
    'max_users' => 500,
    'version' => '2.5.0'
];

foreach ($config as $key => $value) {
    $displayValue = is_bool($value) ? ($value ? 'true' : 'false') : $value;
    echo "Key: [$key] => Value: $displayValue\n";
}
?>
Expected Output
Key: [app_name] => Value: OperateTools
Key: [debug_mode] => Value: true
Key: [max_users] => Value: 500
Key: [version] => Value: 2.5.0

PHP Core Concepts & Feature Breakdown

DomainCore ConceptsPrimary Use CaseOfficial Docs
Variables & Types$var, string, int, boolVariables, string concatenation, type declarationsPHP Types
Arrays & DataIndexed arrays, Associative ['key' => 'val']Key-value mappings, list iteration with foreachPHP Arrays
Functionsfunction name(type $param): returnTypeModular code, default arguments, return value typingPHP Functions
OOP Constructsclass, extends, public/protectedEncapsulation, constructors, inheritance, web frameworksPHP OOP

Keep Practicing

Use the online PHP compiler to test snippet modifications, test array manipulation logic, and build custom functions for backend applications.

Frequently Asked Questions

You can run all snippets instantly in your browser using our Online PHP Compiler without setting up Apache, Nginx, or local PHP runtimes.

Yes. All programs utilize modern PHP standard syntax, typed properties/arguments, short array syntax [], and standard OOP paradigms compatible with PHP 7.4 through PHP 8.x and frameworks such as Laravel and Symfony.

Absolutely. These examples cover essential backend concepts frequently requested during technical evaluations: string operations, prime checks, Fibonacci algorithms, associative array iteration, JSON parsing, and object-oriented inheritance.

Learn PHP by Practicing Examples

PHP powers over 75% of the active web today. Practicing short, clear programs is the most efficient path to mastering PHP backend development. Each snippet focuses on a fundamental building block — from basic variable output and control structures to complex associative arrays, JSON serialization, and object-oriented design.

Beginner Foundations

Learn echo syntax, variable assignment, type coercion, and simple arithmetic operations.

Arrays & Logic

Master key-value arrays, foreach loops, function type hints, and string/math helpers.

OOP & Files

Explore classes, inheritance, visibility, JSON APIs, and file read/write operations.