How to count all array elements in PHP?
Calculates the total number of elements in an array using count().
<?php $items = ['PHP', 'Laravel', 'MySQL', 'Vue.js']; echo "Total Elements: " . count($items) . "\n"; ?>
Total Elements: 4
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.
Who is this for: Web developers, Laravel learners, API engineers, and CS students.
Related Tools:PHP Compiler · PHP Official Manual · JavaScript Examples · Python Examples
Calculates the total number of elements in an array using count().
<?php $items = ['PHP', 'Laravel', 'MySQL', 'Vue.js']; echo "Total Elements: " . count($items) . "\n"; ?>
Total Elements: 4
Shows how to define and access indexed and key-value associative arrays.
<?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";
?>First color: Red User Name: Sarah, Role: Developer
Inserts an element at a specific index in a PHP array using array_splice().
<?php $array = ['Apple', 'Banana', 'Date']; $newItem = 'Cherry'; $position = 2; array_splice($array, $position, 0, $newItem); print_r($array); ?>
Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
[3] => Date
)Combines and appends elements of one array to another using array_merge().
<?php $array1 = ['PHP', 'Python']; $array2 = ['JavaScript', 'C++']; $result = array_merge($array1, $array2); print_r($result); ?>
Array
(
[0] => PHP
[1] => Python
[2] => JavaScript
[3] => C++
)Removes an element at a specific index using unset().
<?php
$fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
// Delete element at index 1 ('Banana')
unset($fruits[1]);
print_r($fruits);
?>Array
(
[0] => Apple
[2] => Cherry
[3] => Date
)Iterates and prints all array elements using a foreach loop and implode().
<?php
$languages = ['PHP', 'JavaScript', 'Python', 'Java'];
echo "Using foreach:\n";
foreach ($languages as $lang) {
echo "- $lang\n";
}
echo "\nJoined String: " . implode(', ', $languages) . "\n";
?>Using foreach: - PHP - JavaScript - Python - Java Joined String: PHP, JavaScript, Python, Java
Locates an element value using array_search() and removes it using unset().
<?php
$colors = ['red', 'green', 'blue', 'yellow'];
$valueToRemove = 'blue';
if (($key = array_search($valueToRemove, $colors)) !== false) {
unset($colors[$key]);
}
print_r($colors);
?>Array
(
[0] => red
[1] => green
[3] => yellow
)Removes an array element and resets array keys using array_values().
<?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); ?>
Array
(
[0] => 10
[1] => 20
[2] => 40
[3] => 50
)Prepends one or more items to the start of an array using array_unshift().
<?php $stack = ['Python', 'Java']; array_unshift($stack, 'PHP', 'C++'); print_r($stack); ?>
Array
(
[0] => PHP
[1] => C++
[2] => Python
[3] => Java
)Compares two arrays regardless of order using array_diff() and count().
<?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";
}
?>Both arrays contain the exact same elements.
Merges arrays while preserving original keys using array_replace() or the union (+) operator.
<?php $array1 = [10 => 'a', 20 => 'b']; $array2 = [30 => 'c', 40 => 'd']; $merged = $array1 + $array2; print_r($merged); ?>
Array
(
[10] => a
[20] => b
[30] => c
[40] => d
)Finds highest and lowest numerical values in an array using max() and min().
<?php $numbers = [42, 17, 89, 5, 64, 23]; $maxVal = max($numbers); $minVal = min($numbers); echo "Maximum Value: $maxVal\n"; echo "Minimum Value: $minVal\n"; ?>
Maximum Value: 89 Minimum Value: 5
Determines if a specific key exists in an associative array using array_key_exists().
<?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";
}
?>Key 'username' exists with value: alex_dev Key 'phone' does not exist.
Counts element occurrences with array_count_values(), sorts descending, and retrieves 2nd item.
<?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"; ?>
Frequencies:
Array
(
[banana] => 4
[apple] => 3
[cherry] => 2
)
Second Most Frequent Element: appleSorts array of objects by property value using usort() and spaceship operator.
<?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";
}
?>Name: Alice, Age: 25 Name: Bob, Age: 30 Name: Charlie, Age: 35
Retrieves last element using array_key_last() without modifying internal array pointer.
<?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"; ?>
Last Element: last Current Pointer Value: first
Extracts the initial elements of two arrays and merges them into a new array.
<?php $arr1 = ['Apple', 'Banana', 'Cherry']; $arr2 = ['Red', 'Yellow', 'Dark Red']; $mergedFirst = [$arr1[0], $arr2[0]]; print_r($mergedFirst); ?>
Array
(
[0] => Apple
[1] => Red
)Sorts array of associative arrays by specific key using usort() and spaceship operator.
<?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);
?>Array
(
[0] => Array
(
[name] => Mouse
[price] => 25
)
[1] => Array
(
[name] => Keyboard
[price] => 75
)
[2] => Array
(
[name] => Laptop
[price] => 1200
)
)Builds a score-based leaderboard by sorting associative array descending.
<?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";
}
?>--- GAME LEADERBOARD --- #1 Diana - 910 pts #2 Bob - 780 pts #3 Charlie - 620 pts #4 Alice - 450 pts
Checks whether an array contains nested child arrays using is_array().
<?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";
?>singleArr is multi: No multiArr is multi: Yes
Constructs nested associative arrays with key-value pairs.
<?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";
?>Employee EMP101 Name: John Doe Skills: PHP, Laravel, MySQL
Groups entries by category key to merge duplicate data values.
<?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);
?>Array
(
[Fruit] => Array
(
[0] => Apple
[1] => Banana
[2] => Orange
)
[Vegetable] => Array
(
[0] => Carrot
)
)Recursively converts nested arrays into an XML string using SimpleXMLElement.
<?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();
?><?xml version="1.0"?> <root><user><name>Alice</name><role>Developer</role><languages><item0>PHP</item0><item1>JavaScript</item1></languages></user></root>
Filters array items against multiple criteria using array_filter().
<?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));
?>Array
(
[0] => Array
(
[id] => 1
[role] => admin
[status] => active
)
[1] => Array
(
[id] => 4
[role] => admin
[status] => active
)
)Locates array index matching specific key-value using array_column() and array_search().
<?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]);
}
?>Found product:
Array
(
[id] => 102
[name] => Desk Chair
[category] => Furniture
)Combines multiple indexed and associative arrays using array_merge().
<?php $frontend = ['HTML', 'CSS', 'JavaScript']; $backend = ['PHP', 'Python', 'Node.js']; $database = ['MySQL', 'PostgreSQL']; $fullStack = array_merge($frontend, $backend, $database); print_r($fullStack); ?>
Array
(
[0] => HTML
[1] => CSS
[2] => JavaScript
[3] => PHP
[4] => Python
[5] => Node.js
[6] => MySQL
[7] => PostgreSQL
)Demonstrates SQL COUNT(*) query pattern using PDO fetchColumn().
<?php $sql = "SELECT COUNT(*) FROM orders WHERE status = 'completed'"; echo "SQL Query: $sql\n"; echo "Execution Pattern: \$count = \$pdo->query(\$sql)->fetchColumn();\n"; ?>
SQL Query: SELECT COUNT(*) FROM orders WHERE status = 'completed' Execution Pattern: $count = $pdo->query($sql)->fetchColumn();
| Domain | Core Concepts | Primary Use Case | Official Docs |
|---|---|---|---|
| Variables & Types | $var, string, int, bool | Variables, 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): returnType | Modular code, default arguments, return value typing | PHP Functions |
| OOP Constructs | class, extends, public/protected | Encapsulation, constructors, inheritance, web frameworks | PHP OOP |
Use the online PHP compiler to test snippet modifications, test array manipulation logic, and build custom functions for backend applications.
[], and standard OOP paradigms compatible with PHP 7.4 through PHP 8.x and frameworks such as Laravel and Symfony. 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.
Learn echo syntax, variable assignment, type coercion, and simple arithmetic operations.
Master key-value arrays, foreach loops, function type hints, and string/math helpers.
Explore classes, inheritance, visibility, JSON APIs, and file read/write operations.