Menu
Coddy logo textTech

Array Size with Count

Part of the Fundamentals section of Coddy's PHP journey — lesson 38 of 71.

When working with arrays, you often need to know how many elements they contain. PHP provides the count() function for exactly this purpose.

<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo count($fruits); // 3
?>

The function returns the total number of elements in the array. This is especially useful when you need to access the last element. Since indexing starts at 0, the last index is always count($array) - 1.

<?php
$colors = ["Red", "Green", "Blue", "Yellow"];

$lastIndex = count($colors) - 1;
echo $colors[$lastIndex]; // Yellow
?>

This approach works regardless of how many items are in the array. Whether you have 3 elements or 300, count() gives you the exact size, making your code flexible and reliable.

challenge icon

Challenge

Easy

Read a line of input containing comma-separated values representing a list of items (e.g., Laptop,Mouse,Keyboard,Monitor,Webcam).

Create an array from this input, then:

  1. Print the total number of items in the array
  2. Print the last element of the array (use count() to calculate the last index)
  3. Print the second-to-last element of the array

Print each result on a separate line.

Example:

If the input is Laptop,Mouse,Keyboard,Monitor,Webcam, the output should be:

5
Webcam
Monitor

If the input is Apple,Banana,Cherry, the output should be:

3
Cherry
Banana

Cheat sheet

The count() function returns the total number of elements in an array:

<?php
$fruits = ["Apple", "Banana", "Cherry"];

echo count($fruits); // 3
?>

Since array indexing starts at 0, the last element is at index count($array) - 1:

<?php
$colors = ["Red", "Green", "Blue", "Yellow"];

$lastIndex = count($colors) - 1;
echo $colors[$lastIndex]; // Yellow
?>

Try it yourself

<?php
// Read the comma-separated input
$input = trim(fgets(STDIN));

// Convert the input string into an array
$items = explode(',', $input);

// TODO: Write your code below
// 1. Print the total number of items using count()
// 2. Print the last element (use count() to calculate the last index)
// 3. Print the second-to-last element

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals