PHP String & JSON Processing

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 sort an array of strings in natural and standard orders?

Run Online

Demonstrates regular sort() versus natural order sorting using natsort().

Program (PHP)
<?php

$files1 = ["img1.png", "img10.png", "img2.png", "img20.png"];
$files2 = $files1;

sort($files1);
echo "Standard Sort:\n" . implode(", ", $files1) . "\n\n";

natsort($files2);
echo "Natural Sort:\n" . implode(", ", $files2) . "\n";
?>
Expected Output
Standard Sort:
img1.png, img10.png, img2.png, img20.png

Natural Sort:
img1.png, img2.png, img10.png, img20.png

PHP String Manipulation Functions

Run Online

Demonstrates built-in PHP functions like strlen, strrev, strtolower, and str_replace.

Program (PHP)
<?php

$text = "Hello PHP World!";

echo "Length: " . strlen($text) . "\n";
echo "Reversed: " . strrev($text) . "\n";
echo "Lowercase: " . strtolower($text) . "\n";
echo "Replaced: " . str_replace("World", "Developers", $text) . "\n";
?>
Expected Output
Length: 16
Reversed: !dlroW PHP olleH
Lowercase: hello php world!
Replaced: Hello PHP Developers!

PHP JSON Encoding and Decoding

Run Online

Converts PHP arrays to JSON strings and decodes JSON back into PHP objects.

Program (PHP)
<?php

$data = [
    "status" => "success",
    "code" => 200,
    "items" => ["Apple", "Banana", "Cherry"]
];

$jsonString = json_encode($data, JSON_PRETTY_PRINT);
echo "JSON Output:\n" . $jsonString . "\n\n";

$decoded = json_decode($jsonString, true);
echo "Decoded Status: " . $decoded['status'] . "\n";
?>
Expected Output
JSON Output:
{
    "status": "success",
    "code": 200,
    "items": [
        "Apple",
        "Banana",
        "Cherry"
    ]
}

Decoded Status: success

How to create a string by joining the array elements using PHP?

Run Online

Joins array elements into a string using a delimiter with implode().

Program (PHP)
<?php

$words = ['PHP', 'is', 'a', 'popular', 'scripting', 'language'];

$sentence = implode(" ", $words);

echo "Joined Sentence: " . $sentence . "\n";
?>
Expected Output
Joined Sentence: PHP is a popular scripting language

How to write PHP program to check for Anagram?

Run Online

Checks if two strings are anagrams using character frequency comparison.

Program (PHP)
<?php

function isAnagram(string $str1, string $str2): bool {
    $s1 = strtolower(str_replace(' ', '', $str1));
    $s2 = strtolower(str_replace(' ', '', $str2));
    return count_chars($s1, 1) === count_chars($s2, 1);
}

$word1 = "listen";
$word2 = "silent";

if (isAnagram($word1, $word2)) {
    echo "'$word1' and '$word2' are Anagrams.\n";
} else {
    echo "'$word1' and '$word2' are NOT Anagrams.\n";
}
?>
Expected Output
'listen' and 'silent' are Anagrams.

How to format Phone Numbers in PHP?

Run Online

Formats raw 10-digit phone number strings into standard (XXX) XXX-XXXX format using preg_replace().

Program (PHP)
<?php

function formatPhoneNumber($phone) {
    $cleaned = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($cleaned) === 10) {
        return preg_replace('/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3', $cleaned);
    }
    return $phone;
}

$rawPhone = "1234567890";
echo "Formatted Phone: " . formatPhoneNumber($rawPhone) . "\n";
?>
Expected Output
Formatted Phone: (123) 456-7890

How to extract the user name from the email ID using PHP?

Run Online

Parses email address strings using strstr() or explode() to retrieve username portion.

Program (PHP)
<?php

$email = "john.doe_dev@example.com";

$username1 = strstr($email, '@', true);

echo "Extracted Username: $username1\n";
?>
Expected Output
Extracted Username: john.doe_dev

How to generate simple random password from a given string using PHP?

Run Online

Generates secure random strings of desired length using random_int() and str_shuffle().

Program (PHP)
<?php

function generatePassword($length = 12) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
    $password = "";
    $maxIndex = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[random_int(0, $maxIndex)];
    }
    return $password;
}

echo "Generated Password: " . generatePassword(12) . "\n";
?>
Expected Output
Generated Password: K8#mP2$xL9!v

How to properly Format a Number With Leading Zeros in PHP?

Run Online

Pads numeric strings with leading zeros using sprintf() or str_pad().

Program (PHP)
<?php

$number = 42;

$formatted1 = sprintf("%06d", $number);
$formatted2 = str_pad($number, 6, "0", STR_PAD_LEFT);

echo "Formatted sprintf: $formatted1\n";
echo "Formatted str_pad: $formatted2\n";
?>
Expected Output
Formatted sprintf: 000042
Formatted str_pad: 000042

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.