PHP Array Functions

Array Functions in PHP

PHP provides a comprehensive suite of built-in array functions designed for common data manipulation tasks such as sorting, merging, searching, and filtering. These functions are an essential part of working with arrays, which are an ordered map data structure in PHP. A list of commonly used PHP array functions is provided below:

 

Adding/Removing Elements:

  • array_push(): Adds one or more elements to the end of an array.
  • array_pop(): Removes and returns the last element of an array.
  • array_unshift(): Adds one or more elements to the beginning of an array.
  • array_shift(): Removes and returns the first element from an array.
  • unset(): Removes a specific element by key or index. Note that this does not re-index a numerically indexed array.

Sorting Arrays:

  • sort(): Sorts an indexed array in ascending order (alphabetical or numerical).
  • rsort(): Sorts an indexed array in descending order.
  • asort(): Sorts an associative array in ascending order, according to the value, while maintaining key association.
  • arsort(): Sorts an associative array in descending order, according to the value, while maintaining key association.
  • ksort(): Sorts an associative array in ascending order, according to the key.
  • krsort(): Sorts an associative array in descending order, according to the key.
  • natsort()/ natcasesort(): Sorts an array using a “natural order” algorithm (case-sensitive and case-insensitive versions, respectively).

Searching and Information:

  • in_array(): Checks if a specified value exists within an array and returns trueor false.
  • array_search(): Searches for a given value and returns the first corresponding key if successful.
  • array_key_exists(): Checks if the specified key or index exists in the array.
  • count()/ sizeof(): Returns the number of elements in an array.
  • array_keys(): Returns all keys or a subset of keys from an array in a new indexed array.
  • array_values(): Returns all values from an array in a new numerically indexed array.

Merging, Slicing, and Modifying:

  • array_merge(): Combines one or more arrays into a single array.
  • array_slice(): Extracts a portion (slice) of an array without modifying the original.
  • array_splice(): Removes a portion of the array and optionally replaces it with something else, modifying the original array.
  • array_filter(): Filters the values of an array using a user-defined callback function.
  • array_map(): Applies a user-defined function to every element of an array and returns a new array with the results.
  • array_reverse(): Returns a new array with the elements in reverse order.
  • array_unique(): Removes duplicate values from an array.