• Function Reference
  • Variable and Type Related Extensions
  • Array Functions

(PHP 4, PHP 5, PHP 7, PHP 8)

array — Create an array

Description

Creates an array. Read the section on the array type for more information on what an array is.

Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical indices are defined, the last overwrites the first.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

Return Values

Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.

Example #1 array() example

Example #2 Automatic index with array()

The above example will output:

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

Example #3 1-based index with array()

Example #4 Accessing an array inside double quotes

Note : array() is a language construct used to represent literal arrays, and not a regular function.
  • array_pad() - Pad array to the specified length with a value
  • list() - Assign variables as if they were an array
  • count() - Counts all elements in an array or in a Countable object
  • range() - Create an array containing a range of elements
  • The array type

User Contributed Notes 38 notes

To Top

PHP Array – How to Use Arrays in Your PHP Projects

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 you start with 0 then the next is 1 ...and so on.

There are different types of arrays in PHP. They are:

  • Numeric/Indexed Arrays
  • Associative Arrays
  • Multidimensional Arrays

Let's look at how each one works in more detail.

What are Numerical or Indexed Arrays?

A numerical array is a type of array which can store strings, numbers, and objects. Here's an example of a numeric array:

From the code above I have a variable of   $cars which stores an array of 5 elements. The var_dump($cars) keyword above will show us the total number of elements we have in the array, the index number of each array, and also the length of each element in the array.

You can also chose to use the echo( ) keyword, but in my case I prefer to use var_dump( ) because it gives a more detailed explanation of the results we get.

localhost_CODE_Arrays_arrays.php---Google-Chrome-6_15_2022-8_44_07-PM

You can also choose to display only one element/item of an array in the web browser by doing this:

The code above follows the same pattern as our definition of an array, which states that it counts from zero. We want to display the element with the index of 4 . Counting from 0 to 4 , we can see that 88 falls under index 4 , indicating that 88 is the number we're seeking and that will be displayed to the browser.

localhost_CODE_Arrays_arrays.php---Google-Chrome-6_17_2022-8_17_58-PM

What are Associative Arrays?

An associative array is a type of array where the key has its own value. In an associative array, we make use of key and value .

Key s are descriptive captions of the array element used to access the value of the array. And value is the value assigned to the array element.

There are situations where you shouldn't use the numeric/indexed array, such as:

  • When you want to store the age of different students along with their names.
  • When you want to record the salaries of your employees.
  • When you want to store the score of a student in different subjects

and so on.  

Suppose we want to assign ages to a group of high school students with their names.

We can use the Associative array method to get it done. For example:

The code above is an example of an associative array. The key s of the array are scott_Mcall , Stalenski , Lydia , Allision , and we used them to assign the age to each student. The value s of the array are 17 , 18 , 16 , and 17 .

What are Multidimensional Arrays?

You can think of a multidimensional array as an array of arrays. This means that every element in the array holds a sub-array within it. In general, multidimensional arrays allow you to store multiple arrays in a single variable.

Suppose we want to store the Names, Registration Numbers, and Emails of some of the staff working in a particular company. We can use multidimensional arrays to archive this.

For example:

Remember, an array starts counting from index 0 . The code above is an example of a multidimensional array because it contains more than one array (an array of arrays) with one single variable of $staff .

The echo $staff [2] [‘Email’] displays the email of the staff that falls into the index of 2 . In our case it will display [email protected] .

If I want to access the Email of the staff in the first array, we'll do the following:

echo $staff [0] ['Email'];

Using the method above, you can access and display any information in the array from the code above.

At this point you should be able to use the three different types of arrays when working on a PHP project.

Thank you for reading.

Have fun coding!

Hello, I go by the alias "Derek". I'm proficient in a wide range of technical skills, which I gained and continued to to hone through self-education.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Using PHP Arrays: A Guide for Beginners

Matt Mickiewicz

In this article, we’ll cover the basics of PHP arrays along with some advanced concepts. We’ll start by introducing you to what an array is, before moving on to the basic syntax of arrays and the different types of indexes available.

Introduction to PHP Arrays

PHP arrays are powerful data structures that allow developers to store and manipulate collections of values. An array is a variable that can hold multiple values, each identified by a unique key or index value.

Arrays in PHP can be used in many ways, such as storing user input, accessing file system directories and files, managing database results and much more. With built-in functions for sorting, searching, filtering and transforming arrays, working with them in PHP is easy.

Basic Concepts: What is an Array?

An array is a collection of variables grouped under one name. It allows the developer to store multiple pieces of data (values) under one variable name instead of creating individual variables for each element.

The array() function accepts any number of comma-separated values. The values contained within an array can be of different data types such as integers, strings, Booleans or even other arrays.

Basic Syntax: Creating and Accessing Arrays

To create an array in PHP, we use the following syntax:

Here’s an example of creating a simple indexed array containing three elements (numbers):

We can access individual elements in an indexed array by their position (or index) within the array. In PHP (and many other programming languages) arrays are zero-indexed, meaning that the first element starts at position zero and not one. To access a particular element by its index, we simply reference it like this:

In this example, we’re accessing the first element of $num_array by its index, which is zero.

Types of Indexes in PHP Arrays

PHP arrays can have different types of indexes. The most commonly used are indexed and associative arrays.

Indexed arrays

An indexed array uses numeric indices to access and store values in an array. Here’s an example:

The above code creates an indexed (numerically keyed) array containing three elements/colors. We can easily access each element/color using its corresponding index within square brackets as shown above.

Associative arrays

On the other hand, associative arrays use named keys/indices instead of numerical ones to store data. This makes it easier for developers to retrieve values according to the keys they set.

Here’s an example:

In the code above, we have an associative array with three key–value pairs. We can access data from this array by using the corresponding key name.

Popular Questions about PHP Arrays

Here are ten of the most popular questions beginning web developers ask about PHP arrays and their answers.

How do I add elements to an existing PHP Array?

You can add elements to an existing PHP indexed or associative array using the array_push() or [] (square bracket) notation. Using array_push() , we can append one or more values to the end of an array.

In this code snippet, we have added two new elements ( banana and grape ) to the existing $fruits array using the array_push() .

Alternatively, you can use square brackets notation by assigning a value to a new index position in an indexed array or setting a new key–value pair for associative arrays.

For example, to add element to indexed arrays, $num_array[] = 67; will add the value 67 at the end of the $num_array .

As an example of adding an element to an associative array, $user_data['country'] = 'United States'; will add a new key–value pair to the $user_data array.

How do I remove elements from an existing PHP Array?

You can remove elements from an existing PHP array using the unset() function or the array_splice() function. Using the unset() function, you can remove a specific element of an indexed or associative PHP array by specifying its index or key respectively.

Here’s an example code snippet:

In this example, we’ve removed the third element ( banana ) of the $fruits array using the unset() function.

Alternatively, you can use the array_splice() function to remove a range of elements from an indexed array. To remove a key–value pair from an associative array, you can also use the unset() function by specifying the key that you want to remove.

In this code snippet, we have removed the 'country' key–value pair from the $user_data associative array using the unset() function.

How do I check if a value exists in an array in PHP?

You can check if a value exists in an array in PHP by using the in_array() function. The in_array() function searches for a given value in an array, and returns true if the value is found and false otherwise.

In this example, we’ve used the in_array() function to check if the value apple exists in the $fruits array. Since apple is present in the array, the condition evaluates to true and the message Apple is in the fruits array is outputted. If apple was not present in the array, the message Apple is not in the fruits array would have been outputted instead. The in_array() function is case-sensitive, so apple and Apple would be treated as two different values. If you want a case-insensitive search, you can use the array_search() function instead.

How do I remove elements from an existing PHP array?

You can remove elements from an existing PHP array using the unset() function or the array_splice() function. Using the unset() function, you can remove a specific element of an indexed or associative PHP array by specifying its index or key respectively. Alternatively, you can use the array_splice() function to remove a range of elements from an indexed array.

To remove a range of elements from an indexed array using the array_splice() function, you need to specify the starting index and the number of elements to remove.

In this example, we’ve removed the elements at indices 1 and 2 (i.e., orange and banana ) from the $fruits array using the array_splice() function.

To remove a key–value pair from an associative array using the unset() function, you can provide the key of the element you want to remove as the argument.

Here is an example code snippet:

This code snippet shows how to remove the city key–value pair from the user_data associative array using the unset() function.

How do you loop through a PHP array?

To loop through a PHP array, you can use a foreach loop like this:

In the above code, $array is the name of the array you want to loop through. $key and $value are variables that will hold the key and value of the current element of the array, respectively. You can then use these variables to perform some action for each element of the array.

How do you sort a PHP array?

Sorting is a common operation when working with arrays in PHP. The following are some of the functions you can use to sort arrays:

  • sort() : sorts the values of an array in ascending order
  • rsort() : sorts the values of an array in descending order
  • asort() : sorts an associative array in ascending order, according to the value
  • arsort() : sorts an associative array in descending order, according to the value
  • ksort() : sorts an associative array in ascending order, according to the key
  • krsort() : sorts an associative array in descending order, according to the key

How to create a multidimensional array in PHP?

To create a multidimensional array in PHP, you simply create an array of arrays.

In the above example, we’ve created a multidimensional array with three arrays, each containing two elements.

Appending Elements to a PHP Array

You can append elements to a PHP array using the [] operator or the array_push() function.

Using the [] operator

Here’s an example of appending elements to an array using the [] operator:

In the code above, we first create an array called $countries with three elements. We then append two more elements to the array using the array[] operator.

Using the array_push() function

Here’s an example of appending elements to an array using the array_push() function:

In the above code, we first create an array called $countries with three elements. We then append two more elements to the array using array_push .

This article has covered some of the most frequently asked questions related to PHP arrays.

Arrays are an essential data structure in PHP, allowing developers to store and manipulate collections of data easily. We’ve learned how to create, add elements to, remove elements from, and loop through arrays in PHP. By using multidimensional arrays, we can organize data into multiple dimensions or layers, and a vast range of built-in functions are available to manipulate and traverse arrays.

Remember, PHP arrays don’t have to be indexed numerically: they can also be associated with keys. We can use these keys to associate values with specific pieces of data, allowing us to retrieve and manipulate specific items easily.

IMAGES

  1. Arrays in PHP

    php array assignment

  2. 21: Using Arrays in PHP to Store Data

    php array assignment

  3. 3 Ways

    php array assignment

  4. Arrays & Array functions

    php array assignment

  5. PHP Tutorial #10 Array Methods

    php array assignment

  6. Understanding Array Push PHP Function With Examples

    php array assignment

VIDEO

  1. How To Work With Arrays In PHP

  2. PHP Array Data Type

  3. 10

  4. PHP Tutorial (& MySQL) #7

  5. PHP Arrays Tutorial

  6. PHP Tutorial for Beginners 10 # Arrays in PHP

COMMENTS

  1. php array assign by copying value or by reference? [duplicate]

    are arrays in php passed by value or by reference? I heard that PHP can select how to assign arrays, depends on array size. It can assign by copying value (as any scalar type) or by reference. PHP always assign array to variables by copying a value, as it says in manual. Or it can assign by reference. ? <?php $a = array(1,2,3); ?>

  2. PHP: Assignment

    Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere. Example #1 Assigning by reference <?php $a = 3; $b = &$a; // $b is a reference to $a print "$a"; // prints 3 print "$b"; // prints 3 $a = 4; // change $a

  3. PHP: array

    Example for 1 dim array: <?php $arr = array( 1, 2, 3, 4, 5 ); foreach ( $arr as $val ) { echo "Value: $Val "; } ?> For multi dim array: <?php $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => ' five '); foreach ( $arr as $key => $value ) { echo "Key: $key, Value: $value"; } ?>

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

  5. Using PHP Arrays: A Guide for Beginners

    Matt Mickiewicz. March 29, 2023. In this article, we’ll cover the basics of PHP arrays along with some advanced concepts. We’ll start by introducing you to what an array is, before moving on ...