Menu
Coddy logo textTech

Accessing Elements by Index

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

Now that you can create arrays, you need to know how to retrieve individual items from them. You access elements using their index—the position number inside square brackets.

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

echo $fruits[0]; // Apple
echo $fruits[1]; // Banana
echo $fruits[2]; // Cherry
?>

Remember that indexing starts at 0, not 1. So the first element is always at index 0, the second at index 1, and so on. This is a common source of confusion for beginners, but it becomes natural with practice.

You can also store an accessed element in a variable:

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

$firstColor = $colors[0];
$lastColor = $colors[2];

echo $firstColor; // Red
echo $lastColor;  // Blue
?>

Accessing the last element requires knowing the array's length. For an array with 3 items, the last index is 2 (since we start counting from 0). You'll learn a more flexible way to find the last element in an upcoming lesson.

challenge icon

Challenge

Easy

Read a line of input containing comma-separated values representing items in a shopping list (e.g., Milk,Bread,Eggs,Butter,Cheese).

Create an array from this input, then:

  1. Print the first item in the list
  2. Print the third item in the list
  3. Store the second item in a variable called $secondItem and print it
  4. Print the item at index 4

Print each result on a separate line.

Example:

If the input is Milk,Bread,Eggs,Butter,Cheese, the output should be:

Milk
Eggs
Bread
Cheese

If the input is Apple,Orange,Grape,Mango,Kiwi, the output should be:

Apple
Grape
Orange
Kiwi

Cheat sheet

Access array elements using their index (position number) inside square brackets. Indexing starts at 0:

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

echo $fruits[0]; // Apple (first element)
echo $fruits[1]; // Banana (second element)
echo $fruits[2]; // Cherry (third element)
?>

You can store accessed elements in variables:

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

$firstColor = $colors[0];
$lastColor = $colors[2];

echo $firstColor; // Red
echo $lastColor;  // Blue
?>

Try it yourself

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

// Create an array from the input
$shoppingList = explode(',', $input);

// TODO: Write your code below
// 1. Print the first item in the list
// 2. Print the third item in the list
// 3. Store the second item in a variable called $secondItem and print it
// 4. Print the item at index 4

?>
quiz iconTest yourself

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

All lessons in Fundamentals