PHP arrays tutorial: Understand PHP arrays in 5 minutes

Hunter Johnson - Aug 26 '22 - - Dev Community

In computer science, an array is a data structure that stores multiple values in a single variable. Think of this as a list of values. Arrays are a powerful tool for storing variables that you can access easily, as you access values by referring to their index number.

In this tutorial, we will introduce you to PHP arrays. We'll show you how to write them and work with them. We'll wrap up with a few hands-on problems.

Today's tutorial at a glance:

What are arrays in PHP?

Simply put, an array in PHP is a list, much like how in In JavaScript, an array is a list of values. For example, you could create an array of integers, like [1, 2, 3, 4, 5], or of mixed data types, like [false, 40, 'purple', $object, 'puppy'].

This makes it possible to hold multiple values under a shared name that can be accessed by referring to an index number, with the first element at index 0.

Arrays

As you can see, the total number of elements in an array is the length of an array. With arrays, length is dynamic and can be changed over time.

PHP treats arrays a bit differently than you might be used to. In PHP, there are multiple kinds of arrays that keep different data types. PHP offers more structured arrays where we can keep sets of “key-value” pairs.

Here are three types of arrays we can use in PHP:

  • Indexed/numeric arrays: arrays with a numeric index
  • Associative arrays: arrays with named keys
  • Multidimensional arrays: arrays that hold one or more arrays

Associative arrays in PHP give us more context and information, making it very useful for web development and other programming needs. All PHP arrays are associative in nature, and you may already be used to this style.

In Python, for example, these are called dictionaries, and in JavaScript, we could code the same behavior with objects.

How to declare arrays in PHP

Before the release of PHP 5.4, we create a new array using the array() function.

<?php
$foo = array(1, 2, 3); // An array of integers created using array fucntion
$bar = ["A", true, 123 => 5]; // Short array syntax, PHP 5.4+
echo $bar[0]; // Returns "A"
echo "\n";
echo $bar[1]; // Returns 1 for true
echo "\n";
echo $bar[123]; // Returns 5
// echo $bar[1234]; // uncommenting this line will give an error because 1234 is inaccessable
?>

-->
A
1
5
Enter fullscreen mode Exit fullscreen mode

Note: We can also declare them with square brackets [ ]. The comma after the last element is optional, and it is usually done for single-line arrays like array(1, 2).

The PHP list() function can also be used to assign variables in a shorter way.

// define array
$array = ['a', 'b', 'c'];

// without list()
$a = $array[0];
$b = $array[1];
$c = $array[2];

// with list()
list($a, $b, $c) = $array;
Enter fullscreen mode Exit fullscreen mode

Tip: list() also works well with foreach to make the construction easier.

$arrays = [[1, 2], [3, 4], [5, 6]];

foreach ($arrays as list($a, $b)) {
   $c = $a + $b;
   echo($c . ', '); // 3, 7, >11,
}

Indexed/Numeric Arrays

Numeric or indexed arrays can store numbers, strings, or objects as array elements, and their index is represented by a number. Take a look at this code example to understand its syntax and run it to see the output.

<html>
   <body>

      <?php
         /* First way to create array. */
         $numbers = array( 1, 2, 3, 4, 5);

         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }

         /* Second way to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";

         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>

   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Associative Arrays

As we discussed before, associated arrays are a lot like indexed arrays, but they are different in terms of their index. Associative arrays in PHP have their index as a string in order to create an association between key-value pairs.

For example, let's use employees' names as the keys in an associative array with salaries as the value.

<html>
   <body>

      <?php
         /* First way to create array. */
         $salaries = array("mark" => 2000, "janet" => 1000, "asma" => 500);

         echo "Salary of mark is ". $salaries['mark'] . "<br />";
         echo "Salary of janet is ".  $salaries['janet']. "<br />";
         echo "Salary of asma is ".  $salaries['asma']. "<br />";

         /* Second way to create array. */
         $salaries['mark'] = "high";
         $salaries['janet'] = "medium";
         $salaries['asma'] = "low";

         echo "Salary of mark is ". $salaries['mark'] . "<br />";
         echo "Salary of janet is ".  $salaries['janet']. "<br />";
         echo "Salary of asma is ".  $salaries['asma']. "<br />";
      ?>

   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Multidimensional Arrays

In a multidimensional array, each element in the main array is also an array. Values in a multidimensional array are accessed using multiple indexes. The syntax declaration of 2-D arrays is as follows:

 $arrayName = array(array(), array()......array())
Enter fullscreen mode Exit fullscreen mode

Let's look at an example of a complex multidimensional array. It is an indexed array containing associative arrays.

<?php
// Define a multidimensional array
$economy = array(
    array(
        "country" => "Germany",
        "currency" => "Euro",
    ),
    array(
        "country" => "Switzerland",
        "currency" => "Swiss Franc",
    ),
    array(
        "country" => "England",
        "currency" => "Pound",
    )
);

echo "Currency of Germany is: " . $economy[0]["currency"]; // Access array at [0] index

?>

-->
Currency of Germany is: Euro
Enter fullscreen mode Exit fullscreen mode

PHP array functions

There are a lot of different things we can do to arrays in PHP. We use array functions to manipulate, modify, and use our arrays in a meaningful way. Let's look at some common operations.

Below, we've listed 10 common array functions, but there are dozens more than you can use.

  • array_keys: return all the keys of an array
  • in_array: checks if a value exists in an array
  • array_reverse: Return an array with elements in reverse order
  • array_unshift: prepend one or more elements to the front of an array
  • array_pop: remove the element off the end of array
  • array_push: remove one or more elements onto the end of array
  • array_diff_assoc: computes the difference of arrays with additional index check
  • array_map: applies the callback to the elements of the given arrays
  • array_merge: merge one or more arrays
  • array_filter: filters array elements with a callback function

Output a structured view of arrays

To print an array in a readable format we use the following:

print_r($arrayName)
Enter fullscreen mode Exit fullscreen mode

This will print our keys and their associated values.

<?php
$fruits = array("Type"=>"Citrus",1=>"Orange",2=>"Grapefruit",3=>"Lemon");//initializing associative array
print_r($fruits);
?>

-->
Array
(
    [Type] => Citrus
    [1] => Orange
    [2] => Grapefruit
    [3] => Lemon
)
Enter fullscreen mode Exit fullscreen mode

Get the length of an array

To print the length of our arrays, we can use the count() function.

count ( Countable|array $value , int $mode = COUNT_NORMAL ) : int
Enter fullscreen mode Exit fullscreen mode
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

-->
82
Enter fullscreen mode Exit fullscreen mode

Accessing array elements

Array elements can be accessed using array[key].

<?php
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

-->
string(3) "bar"
int(24)
string(3) "foo"
Enter fullscreen mode Exit fullscreen mode

Return all the values of an array

We can return the values of our array with the PHP function array_values.

array_values ( array $array ) : array
Enter fullscreen mode Exit fullscreen mode
<?php
$array = array("size" => "M", "color" => "yellow");
print_r(array_values($array));
?>

-->
Array
(
    [0] => M
    [1] => yellow
)
Enter fullscreen mode Exit fullscreen mode

Looping through arrays

When working with arrays, it's common to iterate through an array and perform something on the elements, such as to add them or display them. The most common way to iterate through an array in PHP is using foreach.

You can also use a for loop, but foreach is generally easier to write and read.

foreach ($array as $key => $value) {
    echo "Key is $key.";
    echo "Value is $value.";
}
Enter fullscreen mode Exit fullscreen mode

What to learn next

You should now have a good idea of how arrays work in PHP, and you’re ready to tackle more advanced concepts. Next, we recommend learning the following:

  • Combining array functions
  • Converting to arrays
  • Indexed arrays without key
  • Defining classes in PHP

To get started with these concepts and more, check out Educative’s course Learn PHP from Scratch. This highly interactive course introduces you to fundamental concepts of PHP. It begins with a simple Hello world program and proceeds to cover common concepts such as Conditional Statements, and Loop Statements.

By the time you're done, you'll have a good grip on the basics of PHP and will be ready to study advanced concepts.

Happy learning!

Continue reading about PHP and arrays on Educative

Start a discussion

What do you want to learn next about PHP? Was this article helpful? Let us know in the comments below!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player