PHP Array Functions - Complete Reference
Arrays are a fundamental data structure in PHP used to store multiple values in a single variable. PHP provides a rich set of built-in array functions to manipulate, transform, and analyze array data efficiently. This tutorial offers a complete reference guide to PHP array functions, including practical examples for common functions like count(), array_merge(), and more advanced ones like array_map().
Prerequisites
- Basic understanding of PHP syntax and variables
- Familiarity with arrays in PHP
- PHP installed on your machine (version 7.0+ recommended)
Setup Steps
To follow along with the examples in this tutorial, you need a working PHP environment:
- Install PHP on your local machine or use an online PHP sandbox.
- Create a
.phpfile (e.g.,array-functions.php). - Open the file in your preferred code editor.
- Run your PHP scripts via command line
php array-functions.phpor on a web server.
Popular PHP Array Functions with Examples
1. count()
Returns the number of elements in an array.
$fruits = ["apple", "banana", "cherry"];
echo count($fruits); // Output: 3
2. array_merge()
Combines two or more arrays into a single array.
$array1 = ['color' => 'red', 2, 4];
$array2 = ['a', 'b', 'color' => 'green', 'shape' => 'triangle'];
$result = array_merge($array1, $array2);
print_r($result);
/* Output:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => triangle
)
*/
3. array_map()
Applies a callback function to each element of an array and returns a new array.
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squared);
/* Output:
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
*/
4. array_filter()
Filters elements of an array using a callback function.
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even);
/* Output:
Array
(
[1] => 2
[3] => 4
[5] => 6
)
*/
5. in_array()
Checks if a value exists in an array.
$fruits = ["apple", "banana", "cherry"];
if (in_array("banana", $fruits)) {
echo "Banana is in the list.";
}
// Output: Banana is in the list.
Best Practices for Using PHP Array Functions
- Use descriptive variable names: This makes it easier to understand the purpose of each array.
- Choose the right function: Some functions do similar jobs; always select one optimized for your task (e.g.,
array_mapfor transformations,array_filterfor filtering). - Avoid modifying arrays inside loops: Use built-in array functions which are optimized for better performance.
- Check function return values: Functions like
array_search()can returnfalseor integer keys; always use strict checking. - Preserve array keys when needed: Use functions that maintain keys, like
array_filter(), or re-index arrays as necessary usingarray_values().
Common Mistakes When Using PHP Array Functions
- Confusing associative and indexed arrays when mergingβ
array_merge()overwrites values with the same string keys. - Forgetting that
array_filter()preserves keys; numerical arrays might have unexpected keys after filtering. - Assuming array keys start at 0 after certain operations, but keys can be preserved or changed.
- Using
count()on non-arrays without checks, causing warnings or errors. - Passing null or non-callable as a callback to functions like
array_map()orarray_filter().
Interview Questions on PHP Array Functions
Junior Level
-
What does the
count()function return?
It returns the number of elements in an array. -
How do you merge two arrays in PHP?
Using thearray_merge()function. -
What is an associative array?
An array where keys are strings instead of integers. -
How can you check if a value exists in an array?
Using thein_array()function. -
What function would you use to apply a transformation to every element in an array?
array_map().
Mid Level
-
Explain how
array_merge()handles keys when merging associative arrays.
Keys from later arrays overwrite earlier string keys, while numeric keys are re-indexed. -
How does
array_filter()work and is the array re-indexed?
It filters elements based on a callback, preserving keys (i.e., the array is not re-indexed automatically). -
What happens if you pass a non-callable to
array_map()?
PHP will raise a warning or error, as it expects a callable function as the first argument. -
How can you count multidimensional arrays?
By passingCOUNT_RECURSIVEas the second parameter tocount(). -
How to re-index an array after filtering elements?
Usearray_values()to reset the numerical indexes starting from 0.
Senior Level
-
How would you merge arrays while preserving keys including numeric keys in PHP?
You can use the+array union operator, which preserves keys and does not re-index numeric keys, unlikearray_merge(). -
Describe performance considerations when using
array_map()vs looping manually through an array.
array_map()is internally optimized and often faster or more readable than manual loops, especially for simple transformations, but custom logic might require manual looping. -
Explain how to safely check if a value exists in a multidimensional array?
You need to write a recursive function or use PHP iterators becausein_array()checks only one level by default. -
How to detect if an array is associative or indexed in PHP?
Compare the array keys with a range of sequential integers starting at zero; if they differ, the array is associative. -
Explain the difference between
array_map()andarray_walk().
array_map()returns a new array with the transformed elements, whilearray_walk()applies a callback to each element by reference and modifies the original array.
Frequently Asked Questions (FAQ)
Q1: How do PHP array functions handle associative arrays differently than indexed arrays?
Some functions, like array_merge(), treat string keys differently by overwriting values with the same keys, while numeric keys get re-indexed. Others, like array_filter(), preserve keys regardless of array type.
Q2: Can count() be used with non-array types?
While PHP allows count() on other types, it will return 1 for non-null scalars, and 0 for null values. Itβs best to check the variable is an array before using count().
Q3: What is a practical use case of array_map()?
array_map() is ideal for applying the same transformation to every element, such as sanitizing input data, formatting strings, or calculating values on each array item efficiently.
Q4: How do I merge arrays without losing keys?
You can use the array union operator (+) which preserves keys from the left array and does not re-index numeric keys.
Q5: What should I do after filtering an array if I need sequential indexes?
Use array_values() to reset the keys to a sequential 0-based index after filtering.
Conclusion
PHP array functions offer a powerful and efficient way to manipulate arrays for various applications. From counting elements with count(), merging arrays using array_merge(), to transforming arrays with array_map(), understanding these functions is essential for any PHP developer. This tutorial covered the most important functions, best practices, common pitfalls, and interview questions to build your expertise. Keep practicing with these functions to boost your PHP skills and write cleaner, more effective array-handling code.