How to find the maximum and the minimum in a PHP array? 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 Copy Output
Maximum Value: 89
Minimum Value: 5 PHP Indexed and Associative Arrays 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 Copy Output
First color: Red
User Name: Sarah, Role: Developer How to insert a new item in an array on any position in PHP? 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 Copy Output
Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
[3] => Date
) How to append one array to another in PHP? 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 Copy Output
Array
(
[0] => PHP
[1] => Python
[2] => JavaScript
[3] => C++
) How to delete an Element From an Array in PHP? 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 Copy Output
Array
(
[0] => Apple
[2] => Cherry
[3] => Date
) How to print all the values of an array in PHP? 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 Copy Output
Using foreach:
- PHP
- JavaScript
- Python
- Java
Joined String: PHP, JavaScript, Python, Java How to perform Array Delete by Value Not Key in PHP? 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 Copy Output
Array
(
[0] => red
[1] => green
[3] => yellow
) How to remove Array Element and do Re-Indexing in PHP? 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 Copy Output
Array
(
[0] => 10
[1] => 20
[2] => 40
[3] => 50
) How to count all array elements in PHP? 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 Copy Output
Total Elements: 4 How to insert an item at the beginning of an array in PHP? 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 Copy Output
Array
(
[0] => PHP
[1] => C++
[2] => Python
[3] => Java
) How to check if two arrays contain the same elements? 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 Copy Output
Both arrays contain the exact same elements. How to merge two arrays keeping original keys in PHP? 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 Copy Output
Array
(
[10] => a
[20] => b
[30] => c
[40] => d
) How to check a key exists in an array in PHP? 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 Copy 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? 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 Copy 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? 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 Copy 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? 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 Copy 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? 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 Copy Output
Array
(
[0] => Apple
[1] => Red
) How to sort an Array of Associative Arrays by Value of a Given Key in PHP? 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 Copy 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? 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 Copy 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? 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 Copy Output
singleArr is multi: No
multiArr is multi: Yes How to create Multidimensional Associative Array in PHP? 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 Copy Output
Employee EMP101 Name: John Doe
Skills: PHP, Laravel, MySQL How to merge the duplicate value in multidimensional array in PHP? 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 Copy Output
Array
(
[Fruit] => Array
(
[0] => Apple
[1] => Banana
[2] => Orange
)
[Vegetable] => Array
(
[0] => Carrot
)
) How to convert multidimensional array to XML file in PHP? 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 Copy 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? 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 Copy 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? 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 Copy Output
Found product:
Array
(
[id] => 102
[name] => Desk Chair
[category] => Furniture
) How to merge two or more arrays using array_merge()? 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 Copy 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? 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 Copy Output
SQL Query: SELECT COUNT(*) FROM orders WHERE status = 'completed'
Execution Pattern: $count = $pdo->query($sql)->fetchColumn(); PHP Core Concepts & Feature BreakdownDomain Core Concepts Primary Use Case Official Docs Variables & Types $var, string, int, boolVariables, string concatenation, type declarations PHP Types Arrays & Data Indexed arrays, Associative ['key' => 'val'] Key-value mappings, list iteration with foreach PHP Arrays Functions function name(type $param): returnTypeModular code, default arguments, return value typing PHP Functions OOP Constructs class, extends, public/protectedEncapsulation, constructors, inheritance, web frameworks PHP OOP
Keep PracticingUse 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 FoundationsLearn echo syntax, variable assignment, type coercion, and simple arithmetic operations.
Arrays & LogicMaster key-value arrays, foreach loops, function type hints, and string/math helpers.
OOP & FilesExplore classes, inheritance, visibility, JSON APIs, and file read/write operations.