PHP sizeof: How to Count Elements in Arrays with Examples

php sizeof function

The sizeof function in PHP exists to help developers know how many items an array holds.

Understand the sizeof Function in PHP

The sizeof in PHP returns the number of elements in an array.

Here is the syntax:

sizeof(array, mode);
  • array: The input array to measure.
  • mode: Optional. You can use COUNT_RECURSIVE to include elements in subarrays.

It returns an integer that matches the count of elements. If the array is empty, it returns 0.

Here is a quick example:

$items = ["pen", "book", "table"];
echo sizeof($items);

This example outputs 3 because the array holds three items. PHP counts each main element only. It does not check inside other arrays unless you set recursive mode.

The sizeof helps when code logic depends on the array size. You can use it to limit loops or control how many times a process runs. It also acts as a fast way to check if array indexes exist before using them.

Use the sizeof Function in Arrays

Indexed arrays use numeric keys:

$fruits = ["apple", "mango", "banana"];
echo sizeof($fruits);

This returns 3 because the array has three values linked to keys 0, 1, and 2.

Associative arrays use named keys:

$user = ["name" => "Ali", "age" => 25];
echo sizeof($user);

It returns 2 because two key-value pairs exist in the array.

Multidimensional arrays hold arrays inside them:

$data = [
  ["red", "green"],
  ["blue", "yellow"]
];
echo sizeof($data);

This returns 2 because it counts only the top-level elements unless COUNT_RECURSIVE is set.

The sizeof works with objects that implement Countable:

class MyData implements Countable {
    public function count() {
        return 5;
    }
}
$obj = new MyData();
echo sizeof($obj);

This returns 5 because the object’s count() method sets that value.

If the variable is null or an empty array, sizeof returns 0. This stops errors when you count

So, how to handle null or empty arrays with sizeof?

Before PHP 8:

  • If you used sizeof() on something that is not an array or countable object, it returned 1.
  • If it was NULL, it returned 0.

From PHP 8 onward:

  • Using sizeof() on anything that is not an array or a countable object will give an error instead of returning 1.
  • So using it on a number, string, or normal object now causes a TypeError.

The Differences Between sizeof and count

The sizeof is an alias of count. Both behave the same way in normal use. Developers often choose one based on style or readability.

Here is a table that shows you the key differences:

Featuresizeofcount
PurposeAlias of countThe primary function used to count
Syntaxsizeof(array, mode)count(array, mode)
Return ValueNumber of elementsNumber of elements
Use CaseSame as countSame as sizeof

You can use either function. However, count is more common in most PHP code.

Examples of sizeof Function in PHP

Count the Indexed Array Items:

$colors = ["red", "blue", "green", "yellow"];
echo sizeof($colors);

This returns 4 because there are four elements in the array. It counts only top-level values and does not check inside subarrays.

Recursive Count for Multidimensional Array:

$data = [
    ["pen", "pencil"],
    ["book", "paper"]
];
echo sizeof($data, COUNT_RECURSIVE);

This returns 6 because it counts each subarray item along with the top-level arrays.

Count Items in an Object:

class Box implements Countable {
    public function count() {
        return 8;
    }
}
$box = new Box();
echo sizeof($box);

This returns 8 because the count() method defines the value returned by sizeof.

Handle Null Variable:

$var = null;
echo sizeof($var);

This will show you an error. Here is the output:

Uncaught TypeError: sizeof(): Argument #1 ($value) must be of type Countable|array, null given in /index.php

Wrapping Up

In this article, you learned how sizeof works in PHP and how it can count elements in arrays and objects.

Here is a quick recap:

  • sizeof returns the number of elements in an array or Countable object.
  • It is an alias of count and both work the same way.
  • Use it to check the array size before running loops or other logic.
  • It works with indexed, associative, and multidimensional arrays.

FAQs

How to use sizeof to count array elements in PHP?

You can use the sizeof function to get the total number of elements in an array. Example:

$array = array("apple", "banana", "orange");
$count = sizeof($array);
echo $count; // Output: 3

What is the difference between sizeof and count in PHP?

Both functions return the number of elements in an array or object. They are identical in behavior. Example:

$array = array("red", "green", "blue");
echo sizeof($array); // 3
echo count($array);  // 3

Can sizeof handle multidimensional arrays?

Yes, but it only counts elements in the first level unless you use COUNT_RECURSIVE. Example:

$array = array(
    "fruits" => array("apple", "banana"),
    "colors" => array("red", "blue")
);
echo sizeof($array); // 2
echo sizeof($array, COUNT_RECURSIVE); // 6

Similar Reads

PHP mb_strtolower: How to Handle Multibyte Strings Properly

The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…

PHP array_change_key_case: Change Array Key Cases

The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…

Traits in PHP: What They Are & Examples

PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…

PHP is_file Function: Check if a File Exists

If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

PHP trim(): How to remove Whitespace from String

Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

PHP Type Juggling: How it Works Behind the Scenes

PHP type juggling refers to the dynamic system where the type of a variable is determined by its context in…

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

PHP mb_substr Function: How it Works with Examples

You may need to get part of a text when you work with text in PHP. The mb_substr gives you…

PHP Array: Accessing and Managing Elements

PHP arrays are lists or maps that contain multiple values grouped by array keys. They may include integers, strings, booleans,…

Previous Article

JavaScript Unary Operators: How they Work with Examples

Next Article

JavaScript Coding Style Guide for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.