PHP provides a variety of array functions for manipulating and working with arrays. Here are some commonly used array functions in PHP:

1. count()

  • Returns the number of elements in an array. $arr = [1, 2, 3, 4, 5]; $count = count($arr); echo $count; // Output: 5

2. array_push() and array_pop()

  • array_push(): Adds one or more elements to the end of an array.
  • array_pop(): Removes the last element from an array. $arr = [1, 2, 3]; array_push($arr, 4); echo implode(', ', $arr); // Output: 1, 2, 3, 4 $removed = array_pop($arr); echo $removed; // Output: 4

3. array_shift() and array_unshift()

  • array_shift(): Removes the first element from an array.
  • array_unshift(): Adds one or more elements to the beginning of an array. $arr = [1, 2, 3]; array_shift($arr); echo implode(', ', $arr); // Output: 2, 3 array_unshift($arr, 0); echo implode(', ', $arr); // Output: 0, 2, 3

4. array_slice()

  • Returns a portion of an array. $arr = [1, 2, 3, 4, 5]; $slice = array_slice($arr, 2, 2); echo implode(', ', $slice); // Output: 3, 4

5. array_merge()

  • Merges one or more arrays. $arr1 = [1, 2]; $arr2 = [3, 4]; $merged = array_merge($arr1, $arr2); echo implode(', ', $merged); // Output: 1, 2, 3, 4

6. array_reverse()

  • Reverses the order of elements in an array. $arr = [1, 2, 3]; $reversed = array_reverse($arr); echo implode(', ', $reversed); // Output: 3, 2, 1

7. array_search()

  • Searches an array for a given value and returns the corresponding key if successful. $arr = ['a' => 1, 'b' => 2, 'c' => 3]; $key = array_search(2, $arr); echo $key; // Output: b

8. in_array()

  • Checks if a value exists in an array. $arr = [1, 2, 3]; $exists = in_array(2, $arr); echo $exists ? 'Yes' : 'No'; // Output: Yes

9. array_key_exists()

  • Checks if a specific key exists in an array. $arr = ['a' => 1, 'b' => 2, 'c' => 3]; $exists = array_key_exists('b', $arr); echo $exists ? 'Yes' : 'No'; // Output: Yes

10. array_map()

  • Applies a callback function to each element of an array. $arr = [1, 2, 3]; $squared = array_map(function ($value) { return $value ** 2; }, $arr); echo implode(', ', $squared); // Output: 1, 4, 9

These are just a few examples, and PHP has many more array functions. Be sure to check the official PHP documentation for a comprehensive list and detailed explanations of each function.

Tagged in: