Array functions in PHP

Learn via video courses
Topics Covered

Overview

Arrays are one of the most commonly used data structures in programming, and PHP provides a powerful set of functions to work with arrays. An array is a collection of values that can be accessed by an index or a key. In PHP, arrays can be indexed numerically or by a string key. PHP provides several array functions that can be used to manipulate arrays, including adding or removing elements, sorting elements, merging arrays, and more. For example, the array_push() function can be used to add one or more elements to the end of an array, while the array_pop() function can be used to remove the last element from an array.

Introduction

In PHP, an array is a powerful data structure that allows you to store and manipulate a collection of values under a single variable name. Arrays can be indexed numerically or associatively, making them very flexible and useful in a wide range of programming scenarios. PHP provides a comprehensive set of built-in array functions that enable you to perform a wide range of operations on arrays, such as adding and removing elements, sorting, searching, merging, and more. These functions are designed to be efficient and easy to use, allowing you to work with arrays simply and intuitively. Whether you're a beginner or an experienced PHP programmer, understanding how to work with arrays and use array functions effectively is an essential skill that can greatly enhance your coding capabilities.

Installation

The array function is a built-in feature in PHP, so installing it separately is unnecessary. It is available in all versions of PHP and can be used by default. Arrays are an essential data type in PHP, used to store a collection of values in a single variable. They can be created using the array() function or shorthand [] notation. Once created, you can perform various operations on the array, such as adding, removing, or modifying elements, sorting, filtering, and searching for values.

PHP Array Functions

  • array() - creates a new array.
  • count() - returns the number of elements in an array.
  • in_array() - checks if a value exists in an array.
  • 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_shift() - removes and returns the first element of an array.
  • array_unshift() - adds one or more elements to the beginning of an array.
  • array_reverse() - reverses the order of the elements in an array.
  • array_merge() - merges two or more arrays into one array.
  • array_slice() - extracts a slice of an array.
  • array_splice() - removes and replaces elements from an array.
  • array_keys() - returns an array of the keys of an array.
  • array_values() - returns an array of the values of an array.
  • array_flip() - flips the keys and values of an array.
  • array_unique() - removes duplicate values from an array.
  • array_search() - searches for a value in an array and returns its key.
  • array_walk() - applies a user-defined function to each element of an array.
  • array_map() - applies a user-defined function to each element of an array and returns a new array with the results.
  • array_filter() - filters an array using a user-defined function and returns a new array with the filtered values.
  • array_rand() - returns one or more random keys from an array.
  • array() - creates a new array.
  • count() - returns the number of elements in an array.
  • in_array() - checks if a value exists in an array.
  • 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_shift() - removes and returns the first element of an array.
  • array_unshift() - adds one or more elements to the beginning of an array.
  • array_reverse() - reverses the order of the elements in an array.
  • array_merge() - merges two or more arrays into one array.
  • array_slice() - extracts a slice of an array.
  • array_splice() - removes and replaces elements from an array.
  • array_keys() - returns an array of the keys of an array.
  • array_values() - returns an array of the values of an array.
  • array_flip() - flips the keys and values of an array.
  • array_unique() - removes duplicate values from an array.
  • array_search() - searches for a value in an array and returns its key.
  • array_walk() - applies a user-defined function to each element of an array.
  • array_map() - applies a user-defined function to each element of an array and returns a new array with the results.
  • array_filter() - filters an array using a user-defined function and returns a new array with the filtered values.
  • array_reduce() - reduces an array to a single value using a user-defined function.
  • array_column() - returns an array of values from a single column of a multi-dimensional array.
  • array_intersect() - returns an array of the values that exist in two or more arrays.
  • array_diff() - returns an array of the values that exist in one array but not in another.

Now with the help of examples let us read about fa ew of these array functions in detail:

Examples - Important PHP Array Functions

PHP array() function

The array() function in PHP is used to create a new array. Here's the syntax for the array() function:

The array() function can accept one or more values, separated by commas, and returns an array containing those values. Here's an example of using the array() function to create an array of colors:

In this example, the array() function is used to create a new array with three values: "red", "green", and "blue". The array is then assigned to the variable $colors.

PHP array_change_key_case() function ()

The array_change_key_case() function in PHP is used to change the case of all keys in an array. It can be used to convert all keys to uppercase, lowercase, or title case.

Syntax:

Parameters:

  • $array (Required): The array whose keys will be changed.
  • $case (Optional): The case to which the keys will be changed. It can have one of two values: CASE_LOWER (default) or CASE_UPPER. Return Value:

An array with all keys changed to the specified case. Let us see an example below:

Output

In the example code above, we first define an associative array called $names with keys in different cases. We then use array_change_key_case() to convert all keys to lowercase, uppercase, and title case respectively, and print the resulting arrays using print_r().

PHP array_chunk() function

The array_chunk() function in PHP is used to split an array into chunks of a specified size. The resulting array will be a multi-dimensional array where each element is an array of the specified chunk size, with the last chunk possibly being smaller than the specified size if there aren't enough elements remaining.

Here's the syntax for the array_chunk() function:

Here's an example of how to use the array_chunk() function in PHP:

Output

In this example, we define an array of numbers and then use the array_chunk() function to split it into chunks of 3. The resulting multi-dimensional array is then printed out using the print_r() function.

PHP sort() function

The PHP sort() function is a built-in function that is used to sort an array in ascending order. The syntax of the sort() function is:

In this syntax:

  • array &$array: Required. Specifies the array to be sorted.
  • int $sort_flags: Optional. Specifies the sorting behavior. The default value is SORT_REGULAR, which compares items normally.

Here's an example code that demonstrates how to use the sort() function in PHP:

Output

In the above code, we create an array called $fruits that contains some fruit names. We then call the sort() function and pass in the $fruits array as an argument. The sort() function sorts the array in ascending order and modifies the original array.

PHP array_reverse() Function

The PHP array_reverse() function is used to reverse the order of elements in an array. It takes an array as an argument and returns a new array with the elements in reverse order.

Here's the syntax for the array_reverse() function:

Here's an example of how to use the array_reverse() function:

In this example, we have an original array of fruits: 'apple', 'banana', 'cherry', and 'date'. We pass this array to the array_reverse() function, which returns a new array with the elements in reverse order: 'date', 'cherry', 'banana', and 'apple'.

PHP array_intersect() Function

PHP's array_intersect() function is used to find the common values between two or more arrays. It compares the values of the arrays and returns an array containing only the values that are present in all arrays. Syntax:

Parameters:

  • array1: The first array to compare
  • array2: The second array to compare
  • ...: Additional arrays to compare (optional)

Return Value:

The function returns an array containing the common values between the given arrays.

Example:

Output

In this example, we have two arrays array1andarray1 and array2. We pass these two arrays as arguments to the array_intersect() function, which returns an array containing the common values between the two arrays. The output shows that the common values between the two arrays are banana and orange.

PHP array_search() function

PHP's array_search() function is a built-in function that allows you to search an array for a specified value and return the corresponding key if the value is found. The syntax for array_search() is:

Here's an example of using array_search() in PHP code:

In this example, the array_search() function is used to search for the value 'orange' in the fruitsarray.Ifthevalueisfound,thefunctionwillreturnthecorrespondingkey,whichisthenstoredinthefruits array. If the value is found, the function will return the corresponding key, which is then stored in the `key` variable. The if statement then checks whether the value was found (i.e., $key is not equal to false) and outputs either the key or a message indicating that the value was not found.

Conclusion

  • Arrays in PHP are versatile and powerful data types that can hold multiple values of different types.
  • PHP provides many built-in functions for working with arrays, including functions for adding, removing, and modifying elements, as well as functions for searching, sorting, and filtering arrays.
  • Some common array functions in PHP include count(), array_push(), array_pop(), array_shift(), array_unshift(), array_merge(), array_slice(), array_splice(), array_filter(), array_map(), array_reduce(), in_array(), and array_search().
  • It is important for developers to have a good understanding of the various array functions available in PHP and their parameters, as this can greatly enhance their productivity and code quality.