Array Functions Reference
Introduction to PHP Array Functions
PHP provides an extensive collection of built-in functions for working with arrays. This reference covers the most commonly used array functions with practical examples and real-world use cases.
Why Array Functions Matter
Arrays are fundamental to PHP programming, and mastering the built-in array functions can:
- Reduce Code Complexity: Replace loops with single function calls
- Improve Performance: Native C implementations are faster than PHP loops
- Prevent Bugs: Well-tested functions handle edge cases
- Enhance Readability: Declarative code is easier to understand
Function Categories
PHP's array functions can be grouped into several categories:
- Creation: Building arrays from various sources
- Information: Getting details about arrays
- Manipulation: Adding, removing, and modifying elements
- Searching: Finding elements and checking existence
- Filtering: Selecting subsets based on criteria
- Sorting: Ordering elements in various ways
- Transformation: Converting and mapping arrays
Array Creation and Basic Operations
Creating Arrays
<?php
// Creating arrays
$fruits = array('apple', 'banana', 'orange');
$colors = ['red', 'green', 'blue']; // Short syntax (PHP 5.4+)
// Associative arrays
$person = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
// Mixed arrays
$mixed = [
'string',
42,
3.14,
true,
['nested', 'array']
];
// Multi-dimensional arrays
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Range function
$numbers = range(1, 10);
$letters = range('a', 'z');
$evens = range(2, 20, 2);
print_r($numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print_r($evens); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
// Array fill
$zeros = array_fill(0, 5, 0); // [0, 0, 0, 0, 0]
$keys = array_fill_keys(['a', 'b', 'c'], 'default'); // ['a' => 'default', 'b' => 'default', 'c' => 'default']
?>
Array Creation Methods Explained:
array() vs []: The square bracket syntax is cleaner and preferred in modern PHP (5.4+). Both create identical arrays.
range() Function:
- Creates arrays of sequential values
- Works with numbers and letters
- Third parameter sets the step/increment
- Useful for generating test data or numeric sequences
array_fill() Functions:
- array_fill(): Creates indexed array with repeated values
- array_fill_keys(): Creates associative array with specified keys
- Perfect for initializing arrays with default values
- Common in caching and configuration scenarios
Array Information Functions
<?php
$fruits = ['apple', 'banana', 'orange'];
$person = ['name' => 'John', 'age' => 30];
// Count elements
echo count($fruits); // 3
echo sizeof($fruits); // 3 (alias of count)
// Check if array
var_dump(is_array($fruits)); // true
var_dump(is_array('string')); // false
// Check if empty
var_dump(empty([])); // true
var_dump(empty($fruits)); // false
// Get array keys
$keys = array_keys($person); // ['name', 'age']
$fruit_keys = array_keys($fruits); // [0, 1, 2]
// Get array values
$values = array_values($person); // ['John', 30]
// Check if key exists
var_dump(array_key_exists('name', $person)); // true
var_dump(isset($person['name'])); // true
// Get array info
function getArrayInfo($array) {
return [
'count' => count($array),
'is_indexed' => array_keys($array) === range(0, count($array) - 1),
'is_associative' => count(array_filter(array_keys($array), 'is_string')) > 0,
'keys' => array_keys($array),
'values' => array_values($array)
];
}
print_r(getArrayInfo($fruits));
print_r(getArrayInfo($person));
?>
Information Functions Deep Dive:
count() vs sizeof(): They're identical - sizeof() is an alias. Use count() for consistency with other languages.
is_array() Importance: Always verify array type before array operations to prevent errors, especially with user input or function returns.
empty() Considerations:
- Returns true for empty arrays
- Also true for null, false, 0, "0", ""
- Use count() === 0 for explicit empty array check
array_key_exists() vs isset():
- array_key_exists(): Returns true even if value is null
- isset(): Returns false if value is null
- Use array_key_exists() when null values are valid
Indexed vs Associative Detection:
- Indexed: Keys are sequential integers starting from 0
- Associative: Has at least one string key
- Mixed: Can have both numeric and string keys
Array Manipulation
Adding and Removing Elements
<?php
$fruits = ['apple', 'banana'];
// Add to end
array_push($fruits, 'orange'); // ['apple', 'banana', 'orange']
$fruits[] = 'grape'; // Alternative syntax
// Add to beginning
array_unshift($fruits, 'mango'); // ['mango', 'apple', 'banana', 'orange', 'grape']
// Remove from end
$last = array_pop($fruits); // Returns 'grape', array becomes ['mango', 'apple', 'banana', 'orange']
// Remove from beginning
$first = array_shift($fruits); // Returns 'mango', array becomes ['apple', 'banana', 'orange']
// Remove specific elements
$numbers = [1, 2, 3, 4, 5];
unset($numbers[2]); // Removes element at index 2, array becomes [1, 2, 4, 5] with gaps
// Re-index array after unset
$numbers = array_values($numbers); // [1, 2, 4, 5] with consecutive keys
// Array splice (remove and/or insert)
$colors = ['red', 'green', 'blue', 'yellow'];
$removed = array_splice($colors, 1, 2, ['purple', 'pink']);
// $removed = ['green', 'blue']
// $colors = ['red', 'purple', 'pink', 'yellow']
// Insert without removing
$fruits = ['apple', 'banana', 'orange'];
array_splice($fruits, 1, 0, ['grape', 'mango']);
// $fruits = ['apple', 'grape', 'mango', 'banana', 'orange']
// Advanced manipulation
function insertAt($array, $index, $value) {
return array_splice($array, $index, 0, $value);
}
function removeByValue($array, $value) {
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
return array_values($array);
}
return $array;
}
$test = ['a', 'b', 'c', 'd'];
insertAt($test, 2, 'X'); // ['a', 'b', 'X', 'c', 'd']
$test = removeByValue($test, 'b'); // ['a', 'X', 'c', 'd']
?>
Manipulation Functions Analysis:
Stack Operations (LIFO - Last In, First Out):
- array_push(): Add to end (push onto stack)
- array_pop(): Remove from end (pop from stack)
- Use [] syntax instead of array_push() for single elements
Queue Operations (FIFO - First In, First Out):
- array_unshift(): Add to beginning (enqueue)
- array_shift(): Remove from beginning (dequeue)
- Note: shift/unshift re-index numeric keys
unset() Behavior:
- Removes element but preserves keys
- Creates gaps in indexed arrays
- Use array_values() to re-index
- For associative arrays, gaps are usually fine
array_splice() Power:
- Swiss Army knife of array manipulation
- Can remove, replace, and insert in one operation
- Modifies original array
- Returns removed elements
- Re-indexes numeric keys automatically
Array Merging and Combining
<?php
$fruits1 = ['apple', 'banana'];
$fruits2 = ['orange', 'grape'];
$fruits3 = ['mango', 'kiwi'];
// Merge arrays
$all_fruits = array_merge($fruits1, $fruits2, $fruits3);
// ['apple', 'banana', 'orange', 'grape', 'mango', 'kiwi']
// Merge with + operator (preserves keys)
$array1 = [0 => 'a', 1 => 'b'];
$array2 = [0 => 'c', 2 => 'd'];
$merged = $array1 + $array2; // [0 => 'a', 1 => 'b', 2 => 'd']
// Merge associative arrays
$person1 = ['name' => 'John', 'age' => 30];
$person2 = ['city' => 'New York', 'country' => 'USA'];
$complete_person = array_merge($person1, $person2);
// ['name' => 'John', 'age' => 30, 'city' => 'New York', 'country' => 'USA']
// Merge recursive
$config1 = [
'database' => ['host' => 'localhost', 'port' => 3306],
'cache' => ['enabled' => true]
];
$config2 = [
'database' => ['name' => 'myapp', 'user' => 'admin'],
'logging' => ['level' => 'debug']
];
$merged_config = array_merge_recursive($config1, $config2);
// Combine arrays (keys from one, values from another)
$keys = ['name', 'age', 'city'];
$values = ['John', 30, 'New York'];
$person = array_combine($keys, $values);
// ['name' => 'John', 'age' => 30, 'city' => 'New York']
// Zip arrays together
function array_zip($array1, $array2) {
$result = [];
$count = min(count($array1), count($array2));
for ($i = 0; $i < $count; $i++) {
$result[] = [$array1[$i], $array2[$i]];
}
return $result;
}
$names = ['John', 'Jane', 'Bob'];
$ages = [30, 25, 35];
$zipped = array_zip($names, $ages);
// [['John', 30], ['Jane', 25], ['Bob', 35]]
?>
Merging Strategies Explained:
array_merge() vs + operator:
- array_merge(): Re-indexes numeric keys, preserves string keys
- + operator: Preserves all keys, first array wins conflicts
- Use array_merge() for indexed arrays
- Use + for preserving numeric keys
array_merge_recursive():
- Merges nested arrays recursively
- Creates arrays for duplicate keys instead of overwriting
- Perfect for configuration merging
- Can create unexpected nested arrays
array_combine():
- Creates associative array from two arrays
- First array becomes keys, second becomes values
- Arrays must have equal length
- Useful for converting parallel arrays
Custom Zip Function:
- Pairs elements from multiple arrays
- Similar to Python's zip()
- Stops at shortest array length
- Useful for data transformation
Array Searching and Filtering
Searching Arrays
<?php
$fruits = ['apple', 'banana', 'orange', 'apple'];
$numbers = [10, 20, 30, 40, 50];
// Search for value
$key = array_search('banana', $fruits); // Returns 1
$key = array_search('grape', $fruits); // Returns false
// Check if value exists
$exists = in_array('orange', $fruits); // true
$exists = in_array('grape', $fruits); // false
// Find all keys for a value
$keys = array_keys($fruits, 'apple'); // [0, 3]
// Strict search (type-sensitive)
$mixed = ['1', 2, '3', 4];
$key = array_search(2, $mixed, true); // Returns 1
$key = array_search('2', $mixed, true); // Returns false
// Advanced search functions
function array_find($array, $callback) {
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return null;
}
function array_find_key($array, $callback) {
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $key;
}
}
return null;
}
function array_find_all($array, $callback) {
$result = [];
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
$result[$key] = $value;
}
}
return $result;
}
// Usage examples
$users = [
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Bob', 'age' => 35]
];
$user = array_find($users, function($user) {
return $user['age'] > 30;
}); // ['name' => 'Bob', 'age' => 35]
$adults = array_find_all($users, function($user) {
return $user['age'] >= 25;
}); // All users 25 or older
// Search in multidimensional arrays
function array_search_recursive($needle, $haystack) {
foreach ($haystack as $key => $value) {
if ($needle === $value || (is_array($value) && array_search_recursive($needle, $value) !== false)) {
return $key;
}
}
return false;
}
$data = [
'level1' => [
'level2' => [
'target' => 'found'
]
]
];
$result = array_search_recursive('found', $data); // Returns 'level1'
?>
Search Functions Deep Dive:
array_search() vs in_array():
- array_search(): Returns key if found, false otherwise
- in_array(): Returns boolean existence check
- Both support strict mode (third parameter)
- array_search() useful when you need the position
Strict Mode Importance:
- Without strict: '2' == 2 (true)
- With strict: '2' === 2 (false)
- Prevents type juggling bugs
- Always use strict mode when types matter
Custom Search Functions:
- array_find(): Like JavaScript's find(), returns first match
- array_find_key(): Returns key instead of value
- array_find_all(): Returns all matches, not just first
- Fill gaps in PHP's built-in functions
Recursive Searching:
- Searches nested arrays at any depth
- Returns key at first level where value found
- Useful for configuration and nested data
- Consider performance for deep structures
Filtering Arrays
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter with callback
$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
}); // [2, 4, 6, 8, 10]
$odds = array_filter($numbers, function($n) {
return $n % 2 === 1;
}); // [1, 3, 5, 7, 9]
// Filter without callback (removes falsy values)
$mixed = [0, 1, false, 2, '', 3, null, 4, 0.0];
$truthy = array_filter($mixed); // [1, 2, 3, 4]
// Filter with key
$data = [
'apple' => 5,
'banana' => 3,
'orange' => 8,
'grape' => 2
];
$filtered = array_filter($data, function($value, $key) {
return strlen($key) > 5 && $value > 3;
}, ARRAY_FILTER_USE_BOTH); // ['orange' => 8]
// Custom filter functions
function array_filter_keys($array, $callback) {
return array_filter($array, $callback, ARRAY_FILTER_USE_KEY);
}
function array_reject($array, $callback) {
return array_filter($array, function($value, $key) use ($callback) {
return !$callback($value, $key);
}, ARRAY_FILTER_USE_BOTH);
}
function array_partition($array, $callback) {
$passed = [];
$failed = [];
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
$passed[$key] = $value;
} else {
$failed[$key] = $value;
}
}
return [$passed, $failed];
}
// Usage
$numbers = range(1, 10);
[$evens, $odds] = array_partition($numbers, function($n) {
return $n % 2 === 0;
});
// Remove duplicates
$with_duplicates = [1, 2, 2, 3, 3, 3, 4];
$unique = array_unique($with_duplicates); // [1, 2, 3, 4]
// Remove duplicates from multidimensional array
function array_unique_multidimensional($array, $key) {
$seen = [];
return array_filter($array, function($item) use ($key, &$seen) {
if (in_array($item[$key], $seen)) {
return false;
}
$seen[] = $item[$key];
return true;
});
}
$users = [
['id' => 1, 'name' => 'John'],
['id' => 2, 'name' => 'Jane'],
['id' => 1, 'name' => 'John'], // Duplicate
['id' => 3, 'name' => 'Bob']
];
$unique_users = array_unique_multidimensional($users, 'id');
?>
Filtering Techniques Explained:
array_filter() Modes:
- Default: Filters by value only
- ARRAY_FILTER_USE_KEY: Callback receives key only
- ARRAY_FILTER_USE_BOTH: Callback receives both value and key
- No callback: Removes all falsy values (0, false, null, '', etc.)
Custom Filter Functions:
- array_reject(): Inverse of filter (keeps rejected items)
- array_partition(): Splits into passed/failed groups
- Useful patterns missing from core PHP
- Maintains keys by default
array_unique() Behavior:
- Preserves first occurrence
- Maintains original keys
- Works on simple values only
- For objects/arrays, use custom logic
Multidimensional Unique:
- Custom function for complex data
- Tracks seen values to detect duplicates
- Preserves first occurrence
- Can be adapted for any comparison logic
Array Sorting
Basic Sorting
<?php
$fruits = ['banana', 'apple', 'orange', 'grape'];
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// Sort values (modifies original array)
sort($fruits); // ['apple', 'banana', 'grape', 'orange']
sort($numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
// Reverse sort
rsort($fruits); // ['orange', 'grape', 'banana', 'apple']
// Sort and maintain key associations
$prices = ['apple' => 1.50, 'banana' => 0.80, 'orange' => 2.00];
asort($prices); // Sort by value: ['banana' => 0.80, 'apple' => 1.50, 'orange' => 2.00]
arsort($prices); // Reverse sort by value
// Sort by keys
ksort($prices); // Sort by key: ['apple' => 1.50, 'banana' => 0.80, 'orange' => 2.00]
krsort($prices); // Reverse sort by key
// Natural order sorting
$files = ['file1.txt', 'file10.txt', 'file2.txt', 'file20.txt'];
natsort($files); // ['file1.txt', 'file2.txt', 'file10.txt', 'file20.txt']
// Case-insensitive natural sort
$words = ['Apple', 'banana', 'Cherry', 'date'];
natcasesort($words); // ['Apple', 'banana', 'Cherry', 'date']
// Shuffle array
shuffle($numbers); // Randomizes the order
?>
Sorting Function Guide:
Basic Sorts:
- sort(): Values ascending, re-indexes
- rsort(): Values descending, re-indexes
- Both destroy key associations
Associative Sorts (preserve keys):
- asort(): By value ascending
- arsort(): By value descending
- ksort(): By key ascending
- krsort(): By key descending
Natural Sorting:
- Handles numeric strings intelligently
- file2 comes before file10 (unlike regular sort)
- natsort(): Natural order
- natcasesort(): Case-insensitive natural
shuffle():
- Randomizes array order
- Re-indexes keys
- Uses cryptographically secure randomness in PHP 7.1+
Custom Sorting
<?php
// Sort with custom comparison function
$people = [
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Bob', 'age' => 35],
['name' => 'Alice', 'age' => 25]
];
// Sort by age
usort($people, function($a, $b) {
return $a['age'] <=> $b['age']; // Spaceship operator (PHP 7+)
});
// Sort by multiple criteria
usort($people, function($a, $b) {
// First by age, then by name
if ($a['age'] === $b['age']) {
return strcmp($a['name'], $b['name']);
}
return $a['age'] <=> $b['age'];
});
// Sort associative array by value with custom function
$grades = [
'John' => 85,
'Jane' => 92,
'Bob' => 78,
'Alice' => 92
];
uasort($grades, function($a, $b) {
return $b <=> $a; // Descending order
});
// Sort associative array by key with custom function
uksort($grades, function($a, $b) {
return strcmp($a, $b);
});
// Advanced sorting functions
function array_sort_by($array, $key, $direction = 'asc') {
usort($array, function($a, $b) use ($key, $direction) {
$valueA = is_array($a) ? $a[$key] : $a->$key;
$valueB = is_array($b) ? $b[$key] : $b->$key;
$result = $valueA <=> $valueB;
return $direction === 'desc' ? -$result : $result;
});
return $array;
}
function array_multisort_by($array, $sorts) {
usort($array, function($a, $b) use ($sorts) {
foreach ($sorts as $key => $direction) {
$valueA = is_array($a) ? $a[$key] : $a->$key;
$valueB = is_array($b) ? $b[$key] : $b->$key;
$result = $valueA <=> $valueB;
if ($result !== 0) {
return $direction === 'desc' ? -$result : $result;
}
}
return 0;
});
return $array;
}
// Usage
$students = [
['name' => 'John', 'grade' => 85, 'class' => 'A'],
['name' => 'Jane', 'grade' => 92, 'class' => 'B'],
['name' => 'Bob', 'grade' => 85, 'class' => 'A'],
['name' => 'Alice', 'grade' => 92, 'class' => 'A']
];
// Sort by grade descending, then by name ascending
$sorted = array_multisort_by($students, [
'grade' => 'desc',
'name' => 'asc'
]);
// Sort with custom priority
function array_sort_with_priority($array, $priorities) {
usort($array, function($a, $b) use ($priorities) {
$priorityA = array_search($a, $priorities);
$priorityB = array_search($b, $priorities);
if ($priorityA === false) $priorityA = 999;
if ($priorityB === false) $priorityB = 999;
return $priorityA <=> $priorityB;
});
return $array;
}
$statuses = ['completed', 'pending', 'in_progress', 'cancelled'];
$priority_order = ['pending', 'in_progress', 'completed', 'cancelled'];
$sorted_statuses = array_sort_with_priority($statuses, $priority_order);
?>
Custom Sorting Mastery:
Spaceship Operator (<=>):
- Returns -1, 0, or 1 for less than, equal, or greater than
- Simplifies comparison functions
- Works with numbers, strings, and arrays
- Introduced in PHP 7.0
User Sort Functions:
- usort(): Custom sort, re-indexes
- uasort(): Custom sort, preserves keys
- uksort(): Custom sort by keys
Multi-Criteria Sorting:
- Check primary criterion first
- Use secondary only when primary is equal
- Can chain multiple criteria
- Common pattern for complex data
Comparison Function Rules:
- Return negative if $a should come before $b
- Return positive if $a should come after $b
- Return 0 if they're equal
- Be consistent to avoid undefined behavior
Array Transformation
Mapping and Reducing
<?php
$numbers = [1, 2, 3, 4, 5];
// Map function
$squares = array_map(function($n) {
return $n * $n;
}, $numbers); // [1, 4, 9, 16, 25]
$strings = array_map('strval', $numbers); // ['1', '2', '3', '4', '5']
// Map multiple arrays
$names = ['John', 'Jane', 'Bob'];
$ages = [30, 25, 35];
$people = array_map(function($name, $age) {
return ['name' => $name, 'age' => $age];
}, $names, $ages);
// Reduce function
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // 15
$product = array_reduce($numbers, function($carry, $item) {
return $carry * $item;
}, 1); // 120
// Advanced transformation functions
function array_pluck($array, $key) {
return array_map(function($item) use ($key) {
return is_array($item) ? $item[$key] : $item->$key;
}, $array);
}
function array_group_by($array, $key) {
return array_reduce($array, function($result, $item) use ($key) {
$groupKey = is_array($item) ? $item[$key] : $item->$key;
$result[$groupKey][] = $item;
return $result;
}, []);
}
function array_index_by($array, $key) {
return array_reduce($array, function($result, $item) use ($key) {
$indexKey = is_array($item) ? $item[$key] : $item->$key;
$result[$indexKey] = $item;
return $result;
}, []);
}
// Usage examples
$users = [
['id' => 1, 'name' => 'John', 'department' => 'IT'],
['id' => 2, 'name' => 'Jane', 'department' => 'HR'],
['id' => 3, 'name' => 'Bob', 'department' => 'IT'],
['id' => 4, 'name' => 'Alice', 'department' => 'Finance']
];
$names = array_pluck($users, 'name'); // ['John', 'Jane', 'Bob', 'Alice']
$by_department = array_group_by($users, 'department');
$by_id = array_index_by($users, 'id');
// Flatten arrays
function array_flatten($array, $depth = INF) {
$result = [];
foreach ($array as $item) {
if (is_array($item) && $depth > 0) {
$result = array_merge($result, array_flatten($item, $depth - 1));
} else {
$result[] = $item;
}
}
return $result;
}
$nested = [1, [2, 3], [4, [5, 6]], 7];
$flat = array_flatten($nested); // [1, 2, 3, 4, 5, 6, 7]
// Transpose 2D array
function array_transpose($array) {
return array_map(null, ...$array);
}
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$transposed = array_transpose($matrix);
// [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
?>
Array Set Operations
<?php
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6, 7, 8];
$array3 = [3, 4, 5, 6, 7];
// Intersection (common elements)
$intersection = array_intersect($array1, $array2); // [4, 5]
$intersection_all = array_intersect($array1, $array2, $array3); // [4, 5]
// Intersection with key comparison
$assoc1 = ['a' => 1, 'b' => 2, 'c' => 3];
$assoc2 = ['b' => 2, 'c' => 4, 'd' => 5];
$intersect_assoc = array_intersect_assoc($assoc1, $assoc2); // ['b' => 2]
// Difference (elements in first array not in others)
$diff = array_diff($array1, $array2); // [1, 2, 3]
$diff_all = array_diff($array1, $array2, $array3); // [1, 2]
// Symmetric difference (elements in either array but not both)
function array_symmetric_diff($array1, $array2) {
return array_merge(
array_diff($array1, $array2),
array_diff($array2, $array1)
);
}
$sym_diff = array_symmetric_diff($array1, $array2); // [1, 2, 3, 6, 7, 8]
// Union (all unique elements from both arrays)
function array_union($array1, $array2) {
return array_unique(array_merge($array1, $array2));
}
$union = array_union($array1, $array2); // [1, 2, 3, 4, 5, 6, 7, 8]
// Check if arrays are equal
function arrays_equal($array1, $array2) {
return count($array1) === count($array2) &&
array_diff($array1, $array2) === array_diff($array2, $array1);
}
// Check if array is subset of another
function is_subset($subset, $superset) {
return empty(array_diff($subset, $superset));
}
// Advanced set operations
class ArraySet
{
public static function intersection(...$arrays) {
return array_intersect(...$arrays);
}
public static function union(...$arrays) {
return array_unique(array_merge(...$arrays));
}
public static function difference($array1, ...$arrays) {
return array_diff($array1, ...array_merge(...$arrays));
}
public static function symmetricDifference($array1, $array2) {
return array_merge(
array_diff($array1, $array2),
array_diff($array2, $array1)
);
}
public static function isSubset($subset, $superset) {
return empty(array_diff($subset, $superset));
}
public static function isSuperset($superset, $subset) {
return self::isSubset($subset, $superset);
}
public static function isEqual($array1, $array2) {
return count($array1) === count($array2) &&
empty(array_diff($array1, $array2)) &&
empty(array_diff($array2, $array1));
}
}
?>
Advanced Array Operations
Array Chunking and Slicing
<?php
$numbers = range(1, 20);
// Chunk array into smaller arrays
$chunks = array_chunk($numbers, 5);
// [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
$chunks_with_keys = array_chunk($numbers, 5, true); // Preserve keys
// Slice array
$slice = array_slice($numbers, 5, 10); // Get 10 elements starting from index 5
$slice_with_keys = array_slice($numbers, 5, 10, true); // Preserve keys
// Paginate array
function array_paginate($array, $page, $per_page) {
$offset = ($page - 1) * $per_page;
return [
'data' => array_slice($array, $offset, $per_page),
'current_page' => $page,
'per_page' => $per_page,
'total' => count($array),
'total_pages' => ceil(count($array) / $per_page)
];
}
$data = range(1, 100);
$page1 = array_paginate($data, 1, 10); // First 10 items
$page5 = array_paginate($data, 5, 10); // Items 41-50
// Split array into groups
function array_split($array, $groups) {
$size = ceil(count($array) / $groups);
return array_chunk($array, $size);
}
$split = array_split($numbers, 4); // Split into 4 groups
// Column extraction from 2D array
$users = [
['id' => 1, 'name' => 'John', 'age' => 30],
['id' => 2, 'name' => 'Jane', 'age' => 25],
['id' => 3, 'name' => 'Bob', 'age' => 35]
];
$names = array_column($users, 'name'); // ['John', 'Jane', 'Bob']
$ages = array_column($users, 'age'); // [30, 25, 35]
$name_age = array_column($users, 'age', 'name'); // ['John' => 30, 'Jane' => 25, 'Bob' => 35]
// Custom column function with callback
function array_column_callback($array, $callback) {
return array_map($callback, $array);
}
$full_names = array_column_callback($users, function($user) {
return $user['name'] . ' (Age: ' . $user['age'] . ')';
});
?>
Array Utilities and Helpers
<?php
// Comprehensive array utility class
class ArrayUtils
{
// Get nested value with dot notation
public static function get($array, $key, $default = null) {
if (is_null($key)) {
return $array;
}
if (isset($array[$key])) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if (!is_array($array) || !array_key_exists($segment, $array)) {
return $default;
}
$array = $array[$segment];
}
return $array;
}
// Set nested value with dot notation
public static function set(&$array, $key, $value) {
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
}
// Check if nested key exists
public static function has($array, $key) {
if (is_null($key)) {
return false;
}
if (isset($array[$key])) {
return true;
}
foreach (explode('.', $key) as $segment) {
if (!is_array($array) || !array_key_exists($segment, $array)) {
return false;
}
$array = $array[$segment];
}
return true;
}
// Remove nested key
public static function forget(&$array, $keys) {
$original = &$array;
$keys = (array) $keys;
if (count($keys) === 0) {
return;
}
foreach ($keys as $key) {
if (isset($array[$key])) {
unset($array[$key]);
continue;
}
$parts = explode('.', $key);
$array = &$original;
while (count($parts) > 1) {
$part = array_shift($parts);
if (isset($array[$part]) && is_array($array[$part])) {
$array = &$array[$part];
} else {
continue 2;
}
}
unset($array[array_shift($parts)]);
}
}
// Only get specified keys
public static function only($array, $keys) {
return array_intersect_key($array, array_flip((array) $keys));
}
// Exclude specified keys
public static function except($array, $keys) {
return array_diff_key($array, array_flip((array) $keys));
}
// Array where all values pass truth test
public static function every($array, $callback) {
foreach ($array as $key => $value) {
if (!$callback($value, $key)) {
return false;
}
}
return true;
}
// Array where some values pass truth test
public static function some($array, $callback) {
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return true;
}
}
return false;
}
// Wrap value in array if not already an array
public static function wrap($value) {
if (is_null($value)) {
return [];
}
return is_array($value) ? $value : [$value];
}
// Get first element
public static function first($array, $callback = null, $default = null) {
if (is_null($callback)) {
return empty($array) ? $default : reset($array);
}
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return $default;
}
// Get last element
public static function last($array, $callback = null, $default = null) {
if (is_null($callback)) {
return empty($array) ? $default : end($array);
}
foreach (array_reverse($array, true) as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return $default;
}
}
// Usage examples
$data = [
'user' => [
'profile' => [
'name' => 'John Doe',
'email' => '[email protected]'
],
'settings' => [
'theme' => 'dark',
'notifications' => true
]
]
];
$name = ArrayUtils::get($data, 'user.profile.name'); // 'John Doe'
$theme = ArrayUtils::get($data, 'user.settings.theme', 'light'); // 'dark'
ArrayUtils::set($data, 'user.profile.age', 30);
$hasEmail = ArrayUtils::has($data, 'user.profile.email'); // true
$profile = ArrayUtils::only($data['user'], ['profile']);
$withoutSettings = ArrayUtils::except($data['user'], ['settings']);
$numbers = [2, 4, 6, 8];
$allEven = ArrayUtils::every($numbers, function($n) { return $n % 2 === 0; }); // true
$mixed = [1, 2, 3, 4];
$hasEven = ArrayUtils::some($mixed, function($n) { return $n % 2 === 0; }); // true
?>
This comprehensive array functions reference provides practical examples for working with arrays in PHP, covering everything from basic operations to advanced manipulation techniques.