PHP
π’ PHP sizeof() Function: Alias of count()
The sizeof() function in PHP is an exact construct alias of the count() function. It measures and returns the total number of elements present in an array or countable object.
-
Important Note: Because
sizeof()is an alias, there is zero performance difference or internal logic separation betweensizeof()andcount(). However, usingcount()is generally preferred in standard PHP coding conventions.
π οΈ Basic Syntax & Usage
Pass any array directly to sizeof() to extract the element count:
PHP
// Simple Indexed Array
$frameworks = ["Laravel", "Symfony", "CodeIgniter"];
$totalFrameworks = sizeof($frameworks);
echo "Total Frameworks: " . $totalFrameworks; // Outputs: Total Frameworks: 3
// Associative Array
$serverConfig = [
"host" => "localhost",
"port" => 3306,
"database" => "app_db"
];
echo "Config Items: " . sizeof($serverConfig); // Outputs: Config Items: 3
π Recursive Counting with sizeof()
Just like count(), sizeof() accepts a second mode parameter. Passing COUNT_RECURSIVE (or 1) instructs PHP to count all nested sub-array elements recursively:
PHP
$menu = [
"Front-End" => ["HTML", "CSS", "JS"],
"Back-End" => ["PHP", "Python"]
];
// Normal count (top-level keys only)
echo sizeof($menu); // Outputs: 2
// Recursive count (top-level keys + all child elements)
echo sizeof($menu, COUNT_RECURSIVE); // Outputs: 7
π Comparison & Execution Rules
-
1. Functional Parity:
sizeof($arr)generates identical opcode tocount($arr). -
2. C/C++ Background: Developers coming from C/C++ often prefer
sizeof(), but in PHP, it measures array element quantity rather than memory size in bytes. -
3. TypeError Safety: In PHP 7.2+, passing non-countable types (like scalar variables or
null) triggers a warning or error. Always pass arrays or objects implementingCountable.
π Direct Comparison Table
| Function | Type | Recursive Support | Standard Preference |
|---|---|---|---|
count() |
Built-in Function | Yes (COUNT_RECURSIVE) |
Primary (PSR / PHP Standard) |
sizeof() |
Alias of count() |
Yes (COUNT_RECURSIVE) |
Alternative / Secondary |
-
π Short Summary
-
sizeof()is a direct alias of PHP's built-incount()function. -
It calculates array length and element counts with zero performance overhead compared to
count(). -
Use
COUNT_RECURSIVEmode to traverse and count elements in multidimensional arrays.
