DEV Community

DEV Community

Educative profile image

Posted on Aug 26, 2022 • Originally published at educative.io

PHP arrays tutorial: Understand PHP arrays in 5 minutes

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?

How to declare arrays in php, php array functions.

  • Hands-on PHP array challenges

What to learn next

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.

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

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.

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.

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.

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:

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

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:

This will print our keys and their associated values.

Get the length of an array

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

Accessing array elements

Array elements can be accessed using array[key] .

Return all the values of an array

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

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.

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

  • PHP Tutorial: Get started with PHP from scratch
  • Arrays in Java Tutorial: how to declare & initialize Java arrays
  • Data Structures 101: a tutorial on arrays in JavaScript

Start a discussion

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

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

orololuwa profile image

Setting up a Database Driver, Repository and Implementation of a transaction function for your Go App

Orololuwa - Apr 22

zoltanf profile image

Frontend Frameworks from 2023-2024

Zoltan Fehervari - Apr 30

shaheryaryousaf profile image

What is Python? It's History, Applications and Future

Shaheryar - Apr 3

yuricodesbot profile image

Supabase Security Advisor & Performance Advisor

Yuri - Apr 19

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php associative arrays.

Associative arrays are arrays that use named keys that you assign to them.

Access Associative Arrays

To access an array item you can refer to the key name.

Display the model of the car:

Change Value

To change the value of an array item, use the key name:

Change the year item:

Advertisement

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Display all array items, keys and values:

For a complete reference of all array functions, go to our complete PHP Array Reference .

PHP Exercises

Test yourself with exercises.

Create an associative array containing the age of Peter, Ben and Joe.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Language Reference

Array Operators

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

<?php $a = array( "a" => "apple" , "b" => "banana" ); $b = array( "a" => "pear" , "b" => "strawberry" , "c" => "cherry" ); $c = $a + $b ; // Union of $a and $b echo "Union of \$a and \$b: \n" ; var_dump ( $c ); $c = $b + $a ; // Union of $b and $a echo "Union of \$b and \$a: \n" ; var_dump ( $c ); $a += $b ; // Union of $a += $b is $a and $b echo "Union of \$a += \$b: \n" ; var_dump ( $a ); ?> When executed, this script will print the following: Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" } Union of $a += $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" }

Elements of arrays are equal for the comparison if they have the same key and value.

Example #1 Comparing arrays

  • Array functions

Improve This Page

User contributed notes 7 notes.

To Top

COMMENTS

  1. PHP: Arrays

    Arrays. An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. ... This is done by assigning values to the array ...

  2. PHP Arrays

    In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

  3. PHP Assign array to variables

    As for using explode() with list() or array destructuring, if you are not guaranteed a certain number of elements, it is best practice to declare the 3rd parameter of explode() to limit the number of generated elements. This will not force the production of so many elements; rather it will merely tell php to stop exploding when that number of elements is achieved.

  4. How to Work with PHP Arrays: a Complete Guide

    In PHP, you can add elements to an array by assigning a value to a specific index or by using the array_push() function. Here are a few examples: Here are a few examples: Adding an element using index assignment:

  5. PHP array

    PHP array definition. Arrays are collections of data. A variable can hold only one item at a time. Arrays can hold multiple items. Note: a PHP array is a collection which is used both as a list and a map. PHP has plenty of functions to modify, sort, merge, slice, shuffle the data inside the arrays.

  6. Learn PHP: Learn PHP Arrays Cheatsheet

    In PHP, associative arrays are map-like structures, where keys are associated with values. When we need to access a specific value, we can use the associated key to find it.. In a PHP ordered array, the index locations are the keys. However, the PHP array type also allows us to assign meaningful keys to values.

  7. PHP arrays tutorial: Understand PHP arrays in 5 minutes

    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 ...

  8. PHP Arrays

    By definition, an array is a list of elements. So, for example, you may have an array that contains a list of products. PHP provides you with two types of arrays: indexed and associative. The keys of the indexed array are integers that start at 0. Typically, you use indexed arrays when you want to access the elements by their positions.

  9. PHP Array

    An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ). By default, an array of any variable starts with the 0 index. So whenever you want to call the first value of an array ...

  10. PHP Assignment Operators

    Use PHP assignment operator ( =) to assign a value to a variable. The assignment expression returns the value assigned. Use arithmetic assignment operators to carry arithmetic operations and assign at the same time. Use concatenation assignment operator ( .= )to concatenate strings and assign the result to a variable in a single statement.

  11. PHP Associative Arrays

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  12. Parallel array assignment in PHP

    PHP Multi Dimension Array Assignment. 0. How can I assign an array to another variable in php? 0. Assign array values to PHP variable. 1. Assign array element to variable in PHP. 0. Assigning values to arrays in php. 2. Assigning the same key => value pair to multiple arrays in PHP. 0.

  13. PHP: Array

    The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

  14. How can I assign an array to another variable in php?

    Assign PHP variables in array. 0. assigning array to a variable in php. 0. PHP - Assign variable and use it to assign value to array all in one step. Hot Network Questions How Balanced Would a Magic Item that Changes Size by One Be? Help needed for Lean4 book Interlude exercise Homemade number sequence puzzle ...

  15. Assigning a value to each array element PHP

    Assigning values to arrays in php. 0. Assign Array Value to Variable in PHP. 1. Is there a way to set a value for each element in an array? 0. assign value of multiple variable to form an array variable in php. Hot Network Questions Why is one process ps command showing spaces around a directory instead of slashes?

  16. Destructuring assignment in php for objects / associative arrays

    For PHP 7.0 and below that is beyond the functionality of list.The docs state: list only works on numerical arrays and assumes the numerical indices start at 0.