PHP Arrays & Iteration Patterns

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 create Multidimensional Associative Array in PHP?

Run Online

Constructs nested associative arrays with key-value pairs.

Program (PHP)
<?php

$employees = [
    "EMP101" => [
        "name" => "John Doe",
        "department" => "Engineering",
        "skills" => ["PHP", "Laravel", "MySQL"]
    ],
    "EMP102" => [
        "name" => "Jane Smith",
        "department" => "Design",
        "skills" => ["UI/UX", "Figma", "CSS"]
    ]
];

echo "Employee EMP101 Name: " . $employees["EMP101"]["name"] . "\n";
echo "Skills: " . implode(", ", $employees["EMP101"]["skills"]) . "\n";
?>
Expected Output
Employee EMP101 Name: John Doe
Skills: PHP, Laravel, MySQL

PHP Indexed and Associative Arrays

Run Online

Shows how to define and access indexed and key-value associative arrays.

Program (PHP)
<?php

// Indexed Array
$colors = ["Red", "Green", "Blue"];
echo "First color: " . $colors[0] . "\n";

// Associative Array
$user = [
    "name" => "Sarah",
    "role" => "Developer"
];
echo "User Name: " . $user["name"] . ", Role: " . $user["role"] . "\n";
?>
Expected Output
First color: Red
User Name: Sarah, Role: Developer

How to insert a new item in an array on any position in PHP?

Run Online

Inserts an element at a specific index in a PHP array using array_splice().

Program (PHP)
<?php

$array = ['Apple', 'Banana', 'Date'];
$newItem = 'Cherry';
$position = 2;

array_splice($array, $position, 0, $newItem);

print_r($array);
?>
Expected Output
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Cherry
    [3] => Date
)

How to append one array to another in PHP?

Run Online

Combines and appends elements of one array to another using array_merge().

Program (PHP)
<?php

$array1 = ['PHP', 'Python'];
$array2 = ['JavaScript', 'C++'];

$result = array_merge($array1, $array2);

print_r($result);
?>
Expected Output
Array
(
    [0] => PHP
    [1] => Python
    [2] => JavaScript
    [3] => C++
)

How to delete an Element From an Array in PHP?

Run Online

Removes an element at a specific index using unset().

Program (PHP)
<?php

$fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

// Delete element at index 1 ('Banana')
unset($fruits[1]);

print_r($fruits);
?>
Expected Output
Array
(
    [0] => Apple
    [2] => Cherry
    [3] => Date
)

How to print all the values of an array in PHP?

Run Online

Iterates and prints all array elements using a foreach loop and implode().

Program (PHP)
<?php

$languages = ['PHP', 'JavaScript', 'Python', 'Java'];

echo "Using foreach:\n";
foreach ($languages as $lang) {
    echo "- $lang\n";
}

echo "\nJoined String: " . implode(', ', $languages) . "\n";
?>
Expected Output
Using foreach:
- PHP
- JavaScript
- Python
- Java

Joined String: PHP, JavaScript, Python, Java

How to perform Array Delete by Value Not Key in PHP?

Run Online

Locates an element value using array_search() and removes it using unset().

Program (PHP)
<?php

$colors = ['red', 'green', 'blue', 'yellow'];
$valueToRemove = 'blue';

if (($key = array_search($valueToRemove, $colors)) !== false) {
    unset($colors[$key]);
}

print_r($colors);
?>
Expected Output
Array
(
    [0] => red
    [1] => green
    [3] => yellow
)

How to remove Array Element and do Re-Indexing in PHP?

Run Online

Removes an array element and resets array keys using array_values().

Program (PHP)
<?php

$numbers = [10, 20, 30, 40, 50];

// Delete index 2 (30)
unset($numbers[2]);

// Re-index numerical array keys
$reindexed = array_values($numbers);

print_r($reindexed);
?>
Expected Output
Array
(
    [0] => 10
    [1] => 20
    [2] => 40
    [3] => 50
)

How to count all array elements in PHP?

Run Online

Calculates the total number of elements in an array using count().

Program (PHP)
<?php

$items = ['PHP', 'Laravel', 'MySQL', 'Vue.js'];

echo "Total Elements: " . count($items) . "\n";
?>
Expected Output
Total Elements: 4

How to insert an item at the beginning of an array in PHP?

Run Online

Prepends one or more items to the start of an array using array_unshift().

Program (PHP)
<?php

$stack = ['Python', 'Java'];

array_unshift($stack, 'PHP', 'C++');

print_r($stack);
?>
Expected Output
Array
(
    [0] => PHP
    [1] => C++
    [2] => Python
    [3] => Java
)

How to check if two arrays contain the same elements?

Run Online

Compares two arrays regardless of order using array_diff() and count().

Program (PHP)
<?php

$arr1 = [1, 2, 3, 4];
$arr2 = [4, 3, 2, 1];

$areEqual = (count($arr1) === count($arr2)) && empty(array_diff($arr1, $arr2)) && empty(array_diff($arr2, $arr1));

if ($areEqual) {
    echo "Both arrays contain the exact same elements.\n";
} else {
    echo "Arrays differ.\n";
}
?>
Expected Output
Both arrays contain the exact same elements.

How to merge two arrays keeping original keys in PHP?

Run Online

Merges arrays while preserving original keys using array_replace() or the union (+) operator.

Program (PHP)
<?php

$array1 = [10 => 'a', 20 => 'b'];
$array2 = [30 => 'c', 40 => 'd'];

$merged = $array1 + $array2;

print_r($merged);
?>
Expected Output
Array
(
    [10] => a
    [20] => b
    [30] => c
    [40] => d
)

How to find the maximum and the minimum in a PHP array?

Run Online

Finds highest and lowest numerical values in an array using max() and min().

Program (PHP)
<?php

$numbers = [42, 17, 89, 5, 64, 23];

$maxVal = max($numbers);
$minVal = min($numbers);

echo "Maximum Value: $maxVal\n";
echo "Minimum Value: $minVal\n";
?>
Expected Output
Maximum Value: 89
Minimum Value: 5

How to check a key exists in an array in PHP?

Run Online

Determines if a specific key exists in an associative array using array_key_exists().

Program (PHP)
<?php

$user = [
    'id' => 101,
    'username' => 'alex_dev',
    'email' => 'alex@example.com'
];

if (array_key_exists('username', $user)) {
    echo "Key 'username' exists with value: " . $user['username'] . "\n";
}

if (!array_key_exists('phone', $user)) {
    echo "Key 'phone' does not exist.\n";
}
?>
Expected Output
Key 'username' exists with value: alex_dev
Key 'phone' does not exist.

How to find the second most frequent element in a PHP array?

Run Online

Counts element occurrences with array_count_values(), sorts descending, and retrieves 2nd item.

Program (PHP)
<?php

$arr = ['apple', 'banana', 'apple', 'cherry', 'apple', 'banana', 'banana', 'banana', 'cherry'];

$counts = array_count_values($arr);
arsort($counts);

$keys = array_keys($counts);
$secondMostFrequent = $keys[1] ?? null;

echo "Frequencies:\n";
print_r($counts);
echo "Second Most Frequent Element: " . $secondMostFrequent . "\n";
?>
Expected Output
Frequencies:
Array
(
    [banana] => 4
    [apple] => 3
    [cherry] => 2
)
Second Most Frequent Element: apple

How to sort an array of objects by object fields in PHP?

Run Online

Sorts array of objects by property value using usort() and spaceship operator.

Program (PHP)
<?php

class Person {
    public $name;
    public $age;
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = [
    new Person("Charlie", 35),
    new Person("Alice", 25),
    new Person("Bob", 30)
];

usort($people, function($a, $b) {
    return $a->age <=> $b->age;
});

foreach ($people as $p) {
    echo "Name: {$p->name}, Age: {$p->age}\n";
}
?>
Expected Output
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35

How to print the last value of an array without affecting the pointer?

Run Online

Retrieves last element using array_key_last() without modifying internal array pointer.

Program (PHP)
<?php

$array = ['first', 'second', 'third', 'last'];

$lastKey = array_key_last($array);
$lastValue = $array[$lastKey];

echo "Last Element: " . $lastValue . "\n";
echo "Current Pointer Value: " . current($array) . "\n";
?>
Expected Output
Last Element: last
Current Pointer Value: first

How to merge the first index of an array with the first index of the second array?

Run Online

Extracts the initial elements of two arrays and merges them into a new array.

Program (PHP)
<?php

$arr1 = ['Apple', 'Banana', 'Cherry'];
$arr2 = ['Red', 'Yellow', 'Dark Red'];

$mergedFirst = [$arr1[0], $arr2[0]];

print_r($mergedFirst);
?>
Expected Output
Array
(
    [0] => Apple
    [1] => Red
)

How to sort an Array of Associative Arrays by Value of a Given Key in PHP?

Run Online

Sorts array of associative arrays by specific key using usort() and spaceship operator.

Program (PHP)
<?php

$products = [
    ['name' => 'Laptop', 'price' => 1200],
    ['name' => 'Mouse', 'price' => 25],
    ['name' => 'Keyboard', 'price' => 75]
];

usort($products, function($a, $b) {
    return $a['price'] <=> $b['price'];
});

print_r($products);
?>
Expected Output
Array
(
    [0] => Array
        (
            [name] => Mouse
            [price] => 25
        )

    [1] => Array
        (
            [name] => Keyboard
            [price] => 75
        )

    [2] => Array
        (
            [name] => Laptop
            [price] => 1200
        )

)

How to make a leaderboard using PHP?

Run Online

Builds a score-based leaderboard by sorting associative array descending.

Program (PHP)
<?php

$players = [
    ['name' => 'Alice', 'score' => 450],
    ['name' => 'Bob', 'score' => 780],
    ['name' => 'Charlie', 'score' => 620],
    ['name' => 'Diana', 'score' => 910]
];

usort($players, function($a, $b) {
    return $b['score'] <=> $a['score'];
});

echo "--- GAME LEADERBOARD ---\n";
foreach ($players as $rank => $player) {
    $position = $rank + 1;
    echo "#{$position} {$player['name']} - {$player['score']} pts\n";
}
?>
Expected Output
--- GAME LEADERBOARD ---
#1 Diana - 910 pts
#2 Bob - 780 pts
#3 Charlie - 620 pts
#4 Alice - 450 pts

How to check an array is multidimensional or not in PHP?

Run Online

Checks whether an array contains nested child arrays using is_array().

Program (PHP)
<?php

function isMultidimensional(array $arr): bool {
    foreach ($arr as $element) {
        if (is_array($element)) {
            return true;
        }
    }
    return false;
}

$singleArr = [1, 2, 3];
$multiArr = [1, [2, 3], 4];

echo "singleArr is multi: " . (isMultidimensional($singleArr) ? "Yes" : "No") . "\n";
echo "multiArr is multi: " . (isMultidimensional($multiArr) ? "Yes" : "No") . "\n";
?>
Expected Output
singleArr is multi: No
multiArr is multi: Yes

How to merge the duplicate value in multidimensional array in PHP?

Run Online

Groups entries by category key to merge duplicate data values.

Program (PHP)
<?php

$data = [
    ['category' => 'Fruit', 'item' => 'Apple'],
    ['category' => 'Fruit', 'item' => 'Banana'],
    ['category' => 'Vegetable', 'item' => 'Carrot'],
    ['category' => 'Fruit', 'item' => 'Orange']
];

$merged = [];
foreach ($data as $entry) {
    $cat = $entry['category'];
    if (!isset($merged[$cat])) {
        $merged[$cat] = [];
    }
    $merged[$cat][] = $entry['item'];
}

print_r($merged);
?>
Expected Output
Array
(
    [Fruit] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Orange
        )

    [Vegetable] => Array
        (
            [0] => Carrot
        )

)

How to convert multidimensional array to XML file in PHP?

Run Online

Recursively converts nested arrays into an XML string using SimpleXMLElement.

Program (PHP)
<?php

function arrayToXml($data, &$xmlData) {
    foreach ($data as $key => $value) {
        if (is_numeric($key)) {
            $key = 'item' . $key;
        }
        if (is_array($value)) {
            $subnode = $xmlData->addChild($key);
            arrayToXml($value, $subnode);
        } else {
            $xmlData->addChild("$key", htmlspecialchars("$value"));
        }
    }
}

$data = [
    'user' => [
        'name' => 'Alice',
        'role' => 'Developer',
        'languages' => ['PHP', 'JavaScript']
    ]
];

$xml = new SimpleXMLElement('<root/>');
arrayToXml($data, $xml);

echo $xml->asXML();
?>
Expected Output
<?xml version="1.0"?>
<root><user><name>Alice</name><role>Developer</role><languages><item0>PHP</item0><item1>JavaScript</item1></languages></user></root>

How to search by multiple key => value in PHP array?

Run Online

Filters array items against multiple criteria using array_filter().

Program (PHP)
<?php

$users = [
    ['id' => 1, 'role' => 'admin', 'status' => 'active'],
    ['id' => 2, 'role' => 'editor', 'status' => 'active'],
    ['id' => 3, 'role' => 'admin', 'status' => 'inactive'],
    ['id' => 4, 'role' => 'admin', 'status' => 'active']
];

$searchCriteria = ['role' => 'admin', 'status' => 'active'];

$filtered = array_filter($users, function($user) use ($searchCriteria) {
    foreach ($searchCriteria as $key => $val) {
        if (!isset($user[$key]) || $user[$key] !== $val) {
            return false;
        }
    }
    return true;
});

print_r(array_values($filtered));
?>
Expected Output
Array
(
    [0] => Array
        (
            [id] => 1
            [role] => admin
            [status] => active
        )

    [1] => Array
        (
            [id] => 4
            [role] => admin
            [status] => active
        )

)

How to search by key=>value in a multidimensional array in PHP?

Run Online

Locates array index matching specific key-value using array_column() and array_search().

Program (PHP)
<?php

$products = [
    ['id' => 101, 'name' => 'Laptop', 'category' => 'Electronics'],
    ['id' => 102, 'name' => 'Desk Chair', 'category' => 'Furniture'],
    ['id' => 103, 'name' => 'Smartphone', 'category' => 'Electronics']
];

$keyIndex = array_search('Desk Chair', array_column($products, 'name'));

if ($keyIndex !== false) {
    echo "Found product:\n";
    print_r($products[$keyIndex]);
}
?>
Expected Output
Found product:
Array
(
    [id] => 102
    [name] => Desk Chair
    [category] => Furniture
)

How to merge two or more arrays using array_merge()?

Run Online

Combines multiple indexed and associative arrays using array_merge().

Program (PHP)
<?php

$frontend = ['HTML', 'CSS', 'JavaScript'];
$backend = ['PHP', 'Python', 'Node.js'];
$database = ['MySQL', 'PostgreSQL'];

$fullStack = array_merge($frontend, $backend, $database);

print_r($fullStack);
?>
Expected Output
Array
(
    [0] => HTML
    [1] => CSS
    [2] => JavaScript
    [3] => PHP
    [4] => Python
    [5] => Node.js
    [6] => MySQL
    [7] => PostgreSQL
)

How to count rows in MySQL table in PHP?

Run Online

Demonstrates SQL COUNT(*) query pattern using PDO fetchColumn().

Program (PHP)
<?php

$sql = "SELECT COUNT(*) FROM orders WHERE status = 'completed'";

echo "SQL Query: $sql\n";
echo "Execution Pattern: \$count = \$pdo->query(\$sql)->fetchColumn();\n";
?>
Expected Output
SQL Query: SELECT COUNT(*) FROM orders WHERE status = 'completed'
Execution Pattern: $count = $pdo->query($sql)->fetchColumn();

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.