PHP Array Cheat Sheet: A Complete Reference

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

Arrays are a fundamental structure in programming, and PHP offers a comprehensive set of functions to manipulate them. In this cheat sheet, we will cover how to work with arrays in PHP, along with functions and tips to make your coding experience smoother.

Basic Array Operations

PHP arrays can hold multiple values under a single name. Here are the basics:

Creating Arrays:

$array = array(value1, value2, ...); 
$array = [value1, value2, ...]; // Short array syntax (PHP 5.4+)

Accessing Values:

$firstValue = $array[0]; // Access first element 

Adding Values:

array_push($array, $value); // At the end
$array[] = $value; // Shortcut for adding at the end
array_unshift($array, $value); // At the beginning

Removing Values:

array_pop($array); // Removes last element
array_shift($array); // Removes first element

Associative Arrays

Associative arrays use keys to access values:

$assocArray = array('key1' => 'value1', 'key2' => 'value2');
$assocArray = ['key1' => 'value1', 'key2' => 'value2']; // Short syntax

Accessing Values by Key:

$value1 = $assocArray['key1']; 

Adding Key-Value Pairs:

$assocArray['key3'] = 'value3'; 

Iterating Over Arrays

There are numerous ways to iterate over arrays:

foreach ($array as $value) {
    // Your code
}
foreach ($assocArray as $key => $value) {
    // Your code
}
for ($i = 0; $i < count($array); $i++) {
    // Access $array[$i]
} 

Useful Array Functions

PHP has a abundance of array functions. Here are some commonly used ones:

  • count() – Get the number of elements in an array
  • sort() – Sorts the array
  • array_merge() – Merges one or more arrays
  • array_diff() – Computes the difference of arrays
  • array_filter() – Filters elements of an array using a callback function
  • array_map() – Applies a callback to the elements of the arrays
  • array_keys() – Returns all the keys of an array
  • array_values() – Returns all the values of an array
  • in_array() – Checks if a value exists in an array

Multidimensional Arrays

Arrays that contain other arrays are multidimensional:

$multiArray = array(
    array('apple', 'banana'),
    array('carrot', 'daikon')
); 

Accessing a multidimensional array:

$apple = $multiArray[0][0]; 

You can use foreach loops or for loops to iterate through multidimensional arrays.

Sorting Arrays

PHP provides several functions to sort arrays:

  • sort() – Sort an indexed array in ascending order
  • rsort() – Sort an indexed array in descending order
  • asort() – Sort an associative array in ascending order, according to the value
  • ksort() – Sort an associative array in ascending order, according to the key
  • arsort() – Sort an associative array in descending order, according to the value
  • krsort() – Sort an associative array in descending order, according to the key

More Advanced Array Functions

For more advanced operations, PHP offers functions such as:

  • array_slice() – Extract a portion of the array
  • array_splice() – Remove a portion of the array and replace it with something else
  • array_search() – Search for a given value and return the first corresponding key if successful
  • array_reduce() – Iteratively reduce the array to a single value using a callback function
  • array_walk() – Apply a user-supplied function to every member of an array

Tips for Working with Arrays in PHP

  • To keep code clean and avoid confusion, consistently use either the array() syntax or the short array syntax [] throughout your code.
  • Remember that PHP array index starts at 0.
  • When using array functions that modify the array pointer (such as next(), end(), reset()), it’s a good habit to manually reset the pointer where needed.
  • For multidimensional arrays, consider using references to make code more readable.
  • Be mindful of performance when dealing with large arrays, especially in loops and when using array functions.
  • When possible, use foreach for its readability and convenience; it doesn’t require resettin`g the array pointer.

While this cheat sheet covers the essentials, PHP has many more array functions that cater to specific needs. Consult the PHP manual on arrays for a complete list of array functions and features.