Image generated with Dall-E 2

PHP count() Catastrophes - When NOT to Use It

Serghei Pogor
5 min readMay 6, 2024

--

Counting arrays in PHP can be a bit tricky sometimes.

As someone who’s spent a lot of time working with PHP, I’ve come across my fair share of challenges when it comes to counting arrays.

You see, the count() function is handy, but it doesn’t always give you the whole story.

Sometimes it misses things or counts things that you didn’t expect.

That’s why it’s crucial to have a few tricks up your sleeve when counting arrays.

The Overloaded Array

Imagine you’re traversing through a massive array in PHP, brimming with thousands of elements.

You decide to use count() to check the array’s size before diving in. Sounds innocent enough, right? Wrong! 🚫

Here’s why:

$massiveArray = [...]; // Imagine thousands of elements here
$arraySize = count($massiveArray);
if ($arraySize > 1000) {
// Do something fancy
}

The problem here is that count() iterates through the entire array to determine its size.

With thousands of elements, this operation can be painfully slow, causing your application to grind to a halt. 😱

So, how do we navigate this perilous situation?

Fear not, brave coder! We can simply replace count() with the sizeof() function, which returns the number of elements in an array without iterating through it.

Let’s hoist the sails and rewrite our code:

$massiveArray = [...]; // Imagine thousands of elements here
$arraySize = sizeof($massiveArray);
if ($arraySize > 1000) {
// Do something fancy
}

Ah, much better!

By using sizeof(), we’ve dodged the performance iceberg and kept our PHP ship sailing smoothly. ⚓️

So, remember, when dealing with massive arrays in PHP, opt for sizeof() over count() to keep your code running at full speed ahead! 🚀

The Multidimensional Maze

Imagine you’re sailing through a multidimensional array, exploring its depths for hidden treasures. 🏴‍☠️

You want to know how many elements it holds in total, so you turn to count(). But wait! Using count() on a multidimensional array might not give you the result you’re looking for.

$multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
$totalElements = count($multiArray);
echo "Total elements in the array: $totalElements";

At first glance, it seems like smooth sailing, right? But alas, count() only counts the elements in the first dimension of the array. It doesn’t dive deeper into the nested arrays. ⛵️

But fret not, intrepid sailor!

We can navigate this multidimensional maze with ease. Enter the RecursiveArrayIterator and iterator_count() combo. Let’s splice the code:

$multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($multiArray));
$totalElements = iterator_count($iterator);
echo "Total elements in the array: $totalElements";

Ahoy! By using the power of iterators, we can traverse through each element of our multidimensional array and count them accurately.

Smooth sailing through the multidimensional maze! 🧭🌟

The Empty Array Enigma

Imagine you’re walking through your code, and you see an array up ahead. Your job to check if it’s empty.

You think, “Hmm, I’ll just use count()!”

But be careful!

$emptyArray = [];
if (count($emptyArray) === 0) {
echo "The array be empty!";
} else {
echo "The array be full of treasure!";
}

At first glance, it seems like smooth sailin’, right?

But alas! Using count() to check if an array be empty be like tryin’ to catch a mermaid with a fish net — it just doesn’t work! 🧜‍♀️

But fear not, brave buccaneer! We have a mighty weapon in our arsenal: the empty() function. With a single blow, it can vanquish the empty array of demons!

Let’s rewrite our code and set sail for victory:

$emptyArray = [];
if (empty($emptyArray)) {
echo "The array be empty!";
} else {
echo "The array be full of treasure!";
}

Ahoy! With empty(), we can navigate the empty array waters with ease, avoiding the jaws of the dreaded dragons.️

The Total Count Temptation

Picture this: you’re exploring your PHP code and stumble upon an array filled with all sorts of stuff: numbers, words, even some yes/no signals. You’re curious, so you want to know how many things are in this array. “Hmm, I’ll just use count()!” you think.

But hold on a sec!

$temptingArray = [42, 'hello', true];
$totalCount = count($temptingArray);
echo "The total count of items is: $totalCount";

Looks easy, right? But watch out! count() counts everything, no matter what it is.

So, in this case, it’ll say there are 3 things in the array, including numbers, words, and signals.

But don’t walk the plank just yet!

We’ve got a trusty tool: the array_count_values() function. This gem counts how many times each different thing appears in the array.

$temptingArray = [42, 'hello', true];
$valueCounts = array_count_values($temptingArray);
$totalCount = count($valueCounts);
echo "The total count of items is: $totalCount";

Ahoy! With array_count_values(), we can count only the different things in the array.

The Tricky Query Count

Imagine ye be trekking through yer PHP code, and ye find a query result from yer database.

It’s like a chest of gold, waiting to be counted. Yer task: to count the rows fetched by this query. Ye think, “Arr, I’ll just use count()!” But hold yer course!

$queryResult = $db->query("SELECT * FROM treasures");
$rowCount = count($queryResult);
echo "The number of rows is: $rowCount";

Seems simple, aye? But beware! count() might not give ye the true count. It could count other things besides rows.

But fear not, for we have a trusty tool: the rowCount() method. This loyal mate can accurately count the rows returned by yer query.

Let’s adjust course and rewrite our code:

$queryResult = $db->query("SELECT * FROM treasures");
$rowCount = $queryResult->rowCount();
echo "The number of rows is: $rowCount";

Ahoy! With rowCount(), we can navigate the query seas and count rows accurately.

Mastering the art of counting arrays in PHP is not just about knowing how to use the count() function.

It’s about understanding the nuances of array structures and being prepared to navigate through unexpected challenges.

As PHP developers, let’s approach array counting with a critical eye and a willingness to explore alternative solutions.

By doing so, we can ensure the reliability and accuracy of our code, paving the way for smoother sailing in our PHP endeavors.

🔔 Click Subscribe to catch more coding fun.
👏🏻 Love it? Give a big clap.
💬 Got a cool idea or funny coding joke? Drop it in the comments.

Share these tips with your fellow friends to help each other succeed together.

Thanks for hanging out and reading. You rock! 🚀

Hold on a sec!!! Want more of my fun stuff in your inbox? Sign up here! 📩

--

--