PHP Arrays Tutorial
PHP provides a large number of array functions.[1] We use a task-oriented approach to organize and present the most commonly used array functions to provide a quick reference and learning tool. We cover the following:
- PHP Array Basics
- How to add elements to an array.
- How to remove elements from an array.
- How to add, remove, and/or replace elements in an array using PHP's array_splice function.
- How to iterate over arrays using PHP array functions as well as control structures and language constructs.
- How to work with multidimensional arrays in PHP.
- How to search arrays.
- How to sort arrays.
- How to fill arrays with values.
- How to convert arrays to strings.
- How to combine or merge arrays
PHP Array Functions
PHP array functions are listed below with brief descriptions and links to pages with more information and examples.
Function | Description | Page |
---|---|---|
array_push |
Add element(s) to the end of an array. | Add |
array_unshift |
Add element(s) to the beginning of an array. | Add |
array_pop |
Remove an element from the end of an array. | Remove |
array_shift |
Remove an element from the beginning of an array. | Remove |
array_splice |
Add, remove, and/or replace element(s) in an array. | Splice |
array_walk |
Apply callback function to each array element. | Iterate |
array_map |
Create new array by applying callback function to each array element. | Iterate |
array_filter |
Create a new array by screening values from the passed array. | Iterate |
sort , asort , ... |
Sort arrays. Covers all the PHP sort functions. | Sort |
array_search |
Search for a value in an array; return key of match or false. | Search |
in_array |
Search for a value in an array; return true or false. | Search |
array_keys |
Return an array of keys; optional search value argument. | Search |
array_key_exists |
Search for a key in an array; return true or false. | Search |
array_fill |
Create array and fill elements with value you specify. | Fill |
array_fill_keys |
Create array and fill with keys and values. | Fill |
array_pad |
Copy array and fill to specified length with specified value. | Fill |
range |
Create array and fill with a series of values. | Fill |
implode |
Return a string consisting of array values. | Convert |
array_combine |
Create array using first passed array as keys and second as values. | Combine |
array_merge |
Create array by concatenating values of passed arrays. | Combine |
- The PHP Manual provides an alphabetized list of the array functions with brief descriptions and links to more details. ^