PHP arrays allow us to store multiple values under a single variable name. This means that instead of needing to define a variable for each item, you can store them all together using a single variable.

Arrays are populated in key-value pairs. You have to provide what you want to store in the array, the value, and then a unique identifier, or ID, for the item, called the key. Providing back the ID is how you can access the value you stored in the array.

There are three different kinds of arrays that you can create in PHP:

  • Numeric Arrays
  • Associative Arrays
  • Multidimensional Arrays

Let's learn about the differences between these types of arrays.

Numeric Arrays

Numeric arrays are arrays that use a number as the key. That is, when you want to store an item in the array, give it a number as the key and it will be stored there. Keep in mind that the first element in the array has an index of 0, not 1.

Let's define a numeric array:

PHP
<?php $transportation[0] = 'car'; $transportation[1] = 'bike'; $transportation[2] = 'skates'; ?>

Our array is named $transportation and the number in the brackets is the item's key. We set that to the value we want to store in the array.

We can also let PHP automatically fill in the keys in order by using this syntax:

PHP
<?php $transportation = ['car', 'bike', 'skates']; ?>

The end result is the exact same thing. To get back an item from either array, simply call the array and pass in a key:

PHP
<?php $transportation = ['car', 'bike', 'skates']; echo($transportation[1]); ?>
HTML
bike

Associative Arrays

Associative arrays are very similar to numeric arrays except that instead of the keys being numbers, the keys are simply another value of some kind. This means that the value can be, for example, a string.

PHP
<?php $schools['Bob'] = 'NYU'; $schools['Jack'] = 'Columbia'; $schools['Jasmine'] = 'Yale'; ?>

Depending on the situation, you can also opt to define associative arrays in this syntax as well:

PHP
<?php $schools = ['Bob' => 'NYU', 'Jack' => 'Columbia', 'Jasmine' => 'Yale']; ?>

As with before, getting back an array element is as easy as passing in the key.

PHP
<?php $person = 'Jasmine'; $schools = ['Bob' => 'NYU', 'Jack' => 'Columbia', 'Jasmine' => 'Yale']; echo($person . ' attends ' . $schools[$person]); ?>
HTML
Jasmine attends Yale

Checking for Existence of Keys

Sometimes you won't actually know if the associative array contains the key you want to access. If you try to access it anyways, you'll get an error. To avoid this, check for the existence of the key using the isset() function:

PHP
<?php $person = 'Jasmine'; $schools = ['Bob' => 'NYU', 'Jack' => 'Columbia', 'Jasmine' => 'Yale']; if (isset($schools[$person])) { echo($person . ' attends ' . $schools[$person]); } else { // the key does not exist } ?>
HTML
Jasmine attends Yale

The isset() function can be used on anything, not just for checking keys in an associative arrays. You can also check for the existence of variables in general that may have been defined in other files. The function will return a boolean indicating whether or not the variable exists and has a value.

Multidimensional Arrays

Multidimensional arrays is an array in which each element is an array itself. Following our earlier example, we can store an entire array of information, instead of just the name of the school they attend.

PHP
<?php $students = [ [ 'name' => 'Bob', 'school' => 'NYU', 'graduation' => 2019 ], [ 'name' => 'Jack', 'school' => 'Columbia', 'graduation' => 2021 ], [ 'name' => 'Jasmine', 'school' => 'Yale', 'graduation' => 2020 ] ]; $student_id = 1; $student = $students[$student_id]; echo($student['name'] . ' is attending ' . $student['school'] . ' and graduating in ' . $student['graduation']); ?>
HTML
Jack is attending Columbia and graduating in 2021

Alternatively, instead of using their student id as the key, you can also use their name:

PHP
<?php $students = [ 'Bob' => [ 'school' => 'NYU', 'graduation' => 2019 ], 'Jack' => [ 'school' => 'Columbia', 'graduation' => 2021 ], 'Jasmine' => [ 'school' => 'Yale', 'graduation' => 2020 ] ]; $student_name = 'Bob'; $student = $students[$student_name]; echo($student_name . ' is attending ' . $student['school'] . ' and graduating in ' . $student['graduation']); ?>
HTML
Bob is attending NYU and graduating in 2019

Functions

PHP provides us built-in functions that make working with arrays much easier. Let's take a look at a few of these.

print_r

The print_r, meaning to print in human-readable form, can print out the entire array for us.

PHP
<?php $students = [ 'Bob' => [ 'school' => 'NYU', 'graduation' => 2019 ], 'Jack' => [ 'school' => 'Columbia', 'graduation' => 2021 ], 'Jasmine' => [ 'school' => 'Yale', 'graduation' => 2020 ] ]; print_r($students); ?>
HTML
Array ( [Bob] => Array ( [school] => NYU [graduation] => 2019 ) [Jack] => Array ( [school] => Columbia [graduation] => 2021 ) [Jasmine] => Array ( [school] => Yale [graduation] => 2020 ) )

Sort

Sorting arrays in PHP can be complicated given how many functions there are for it, but once you find the one you need, it gets the job done. Here are just some of the sorting functions available to you:

  • sort(): Sorts a numeric array by key, low to high.
  • rsort(): Sorts a numeric array by key, high to low.
  • array_multisort(): Sorts multi-dimensional arrays by value.
  • asort(): Sorts associative arrays by value, low to high.
  • arsort(): Sorts associative arrays by value, high to low.
  • ksort(): Sorts an array by key, low to high.
  • krsort(): Sorts an array by key, high to low.

Let's sort our earlier array:

PHP
<?php $students = [ 'Bob' => [ 'school' => 'NYU', 'graduation' => 2019 ], 'Jack' => [ 'school' => 'Columbia', 'graduation' => 2021 ], 'Jasmine' => [ 'school' => 'Yale', 'graduation' => 2020 ] ]; arsort($students); print_r($students); ?>
HTML
Array ( [Jasmine] => Array ( [school] => Yale [graduation] => 2020 ) [Bob] => Array ( [school] => NYU [graduation] => 2019 ) [Jack] => Array ( [school] => Columbia [graduation] => 2021 ) )

array_push

Use array_push() to append elements to the end of an array.

PHP
<?php $colors = ['red', 'blue']; array_push($colors, 'green', 'yellow'); print_r($colors); ?>
HTML
Array ( [0] => red [1] => blue [2] => green [3] => yellow )

array_pop

To remove and return the last element in an array, use array_pop().

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow']; $last = array_pop($colors); print_r($colors); echo($last); ?>
HTML
Array ( [0] => red [1] => blue [2] => green ) yellow

array_shift

To instead remove the first element in an array, use array_shift().

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow']; $first = array_shift($colors); print_r($colors); echo($first); ?>
HTML
Array ( [0] => blue [1] => green [2] => yellow ) red

array_unshift

To add an element to be beginning of an array, use array_unshift().

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow']; array_unshift($colors, 'purple'); print_r($colors); ?>
HTML
Array ( [0] => purple [1] => red [2] => blue [3] => green [4] => yellow )

array_merge

To merge two or more arrays together, use array_merge().

PHP
<?php $some_colors = ['red', 'blue', 'green', 'yellow']; $more_colors = ['purple', 'brown', 'white']; $colors = array_merge($some_colors, $more_colors); print_r($colors); ?>
HTML
Array ( [0] => red [1] => blue [2] => green [3] => yellow [4] => purple [5] => brown [6] => white )

array_slice

You can return a selected part, or slice of an array using array_slice().

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow', 'orange']; print_r(array_slice($colors, 1, 2)); ?>
HTML
Array ( [0] => blue [1] => green )

The first parameter is the array you want to slice. The second parameter is the index you want to begin at. The third parameter is the number of elements you want returned back, or the new length.

array_splice

You can replace selected elements of an array with another array using array_splice().

PHP
<?php $words = ['a' => 'apple', 'b' => 'book', 'c' => 'car', 'd' => 'dark']; $replace = ['a' => 'amazing', 'b' => 'bacon']; array_splice($words, 0, 2, $replace); print_r($words); ?>
HTML
Array ( [0] => amazing [1] => bacon [c] => car [d] => dark )

explode

Use the explode() function to take a string and divide it up into an array of elements. Let's say you wanted to break up a text by a comma, also known as the delimiter:

PHP
<?php $text = 'oh,say,can,you,see'; $words = explode(',', $text); print_r($words); ?>
HTML
Array ( [0] => oh [1] => say [2] => can [3] => you [4] => see )

implode

The opposite of explode(), implode() takes an array of strings and returns a single new string, joined by whatever text you want, your delimiter.

PHP
<?php $array = ['oh', 'say', 'can', 'you', 'see']; $text = implode(',', $array); print_r($text); ?>
HTML
oh,say,can,you,see

array_search

Search through an array via a value and get back the key it was associated with using array_search().

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow', 'orange']; echo(array_search('green', $colors)); ?>
HTML
2

The color green was found in the third spot which has an index of 2.

in_array

Simply put, the in_array function tells you if your value is in the array or not.

PHP
<?php $colors = ['red', 'blue', 'green', 'yellow', 'orange']; if (in_array('orange', $colors)) { echo('Color found!'); } else { echo('Color not found!'); } ?>
HTML
Color found!

array_unique

Remove all duplicate values from an array using array_unique().

PHP
<?php $colors = ['red', 'blue', 'red', 'blue']; print_r(array_unique($colors)); ?>
HTML
Array ( [0] => red [1] => blue )

array_reverse

You can reverse the elements in an array using array_reverse.

PHP
<?php $words = ['a' => 'apple', 'b' => 'book', 'c' => 'car', 'd' => 'dark']; print_r(array_reverse($words)); ?>
HTML
Array ( [d] => dark [c] => car [b] => book [a] => apple )

array_map

Use array_map when you want to apply a function to every element in an array to return a new array with them. For example, let's say you wanted to double every number in an array:

PHP
<?php $numbers = [1, 2, 3, 4, 5]; function double($number) { return $number * 2; } print_r(array_map('double', $numbers)); ?>
HTML
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

array_filter

Use the array_filter function to keep or remove elements from an array depending on whether or not that element fulfills a condition you define. Let's say you only want odd numbers:

PHP
<?php $numbers = [1, 2, 3, 4, 5]; function odd($number) { return $number % 2 == 1; } print_r(array_filter($numbers, 'odd')); ?>
HTML
Array ( [0] => 1 [2] => 3 [4] => 5 )

Your function returns true if the element should remain or false if the element should be filtered out.

array_reduce

The array_reduce function is useful for when you want to perform a single operation across an entire array and return a single end result. A perfect example is taking a sum of an array of numbers:

PHP
<?php $numbers = [1, 2, 3, 4, 5]; function sum($carry, $number) { $carry += $number; return $carry; } print_r(array_reduce($numbers, 'sum')); ?>
HTML
15

The way this function works is rather simple. The $carry variable carries over the value of the all the previous iterations. So when we call $carry += $number;, we are adding the current number's value, then returning it to be used in the next element's iteration.

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.