Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

Indexed Arrays in PHP

Indexed Arrays are a data type that contain many different values inside of them. These are useful when we have a list of information we need to work with.

For example, let’s say we want to run echo on all the companies we applied to. We could do something like this:

<?php
  $company1 = "<li>Company A</li>";
  $company2 = "<li>Company B</li>";
  $company3 = "<li>Company C</li>";

  echo $company1;
  echo $company2;
  echo $company3;
?>

This is a lot of repeated code and extra variables. Every time we add a new value we have to add a new variable.

We could fix this by creating one value that contains many values.

<?php
  $companies = array("Company A", "Company B", "Company C");
?>

With our array, we get a specific value in our array using an index value.

Index values for arrays start at 0, not at 1

Since we have three values in our array, we can numbers 0 – 2 at our disposal.

<?php
  $companies = array("<li>Company A</li>", "<li>Company B</li>", "<li>Company C</li>");

  echo $companies[0];
  echo $companies[1];
  echo $companies[2];
?>

It’s also important we learn about the count function.

The count function tells us how many items are in our array.

So for our array, calling we would have a length of 3.

We can print out the length of our array to our page like this:

<?php
  $companies = array("Company A", "Company B", "Company C");

  echo count(companies);
?>

Next we’d want to iterate through this array. Iterating through an array requires looping through it.

<?php
  $companies = array("Company A", "Company B", "Company C");

  for($i = 0; $i <= count(companies); i++) {
    echo companies[i];
  }
?>

Now our code only takes up 4 line, instead of the 7 we started with.

We can also add a new element to our companies array without worrying about adding another echo


<?php
  $companies = array("Company A", "Company B", "Company C", "Company D");

  for($i = 0; i <= count(companies); i++) {
    echo companies[i];
  }
?>

Shorthand syntax for PHP arrays

We can also use shorthand syntax to define PHP arrays:

<?php
  $companies = ["Company A", "Company B", "Company C", "Company D"];
  echo $companies;
?>