Get the count of a PHP array

There are many functions available relating to PHP arrays, and it’s time to replace our $numPosts variable with a dynamic one that uses our new $posts array.

This is an easy one — just call count, passing in the value of the $posts array. Refreshing our page now shows us the correct count of 2.

<?php
$title = 'My Blog';
...
$numPosts = count($posts);
...

We’ll notice that if we only have one record in our posts array as well, the title says 1 posts.

$posts = [
    [
        'title' => 'How to learn PHP',
        'content' => 'This is how you learn PHP.',
    ],
];

This isn’t correct, it should say one post instead of one posts. Let’s replace this logic with a ternary.

We’ll create a new variable that contains our posts text, so let’s call it $postDisplay. We’ll set it equal to a ternary of $numPosts === 1 ? 'post' : 'posts'.

We’’ll then update our $numPostsDisplay variable to look at this new $postDisplay variable.

<?php
...
$postDisplay = $numPosts === 1 ? 'post' : 'posts';
$numPostsDisplay = "$numPosts $postDisplay";
...

Now if we refresh the page, we will correctly see 1 post. And if we add our second post back in, it will correctly say 2 posts.

<?php
$title = 'My Blog';
$posts = [
    [
        'title' => 'How to learn PHP',
        'content' => 'This is how you learn PHP.',
    ],
    [
        'title' => 'How to learn MySQL',
        'content' => 'This is how you learn MySQL.',
    ],
];
$numPosts = count($posts);
$postDisplay = $numPosts === 1 ? 'post' : 'posts';
$numPostsDisplay = "$numPosts $postDisplay";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<pre><?php var_dump($posts) ?></pre>

Check out the very many available built-in functions available for PHP arrays, as these start to make arrays much more powerful than other regular variables.

Complete and Continue