We are still cooking the magic in the way!
PHP Fundamentals
Array Functions
Mastering PHP Array Functions
PHP provides over 70 built-in array functions that make working with arrays powerful and efficient. In this lesson, we'll explore the most useful and commonly used array functions that every PHP developer should know.
Note: Most array functions either modify the original array in place or return a new array. Always check the function documentation to understand its behavior.
Array Transformation Functions
array_map() - Transform Elements
Apply a callback function to each element:
<?php
// Square all numbers
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squared); // [1, 4, 9, 16, 25]
// Convert to uppercase
$names = ["alice", "bob", "charlie"];
$upper = array_map("strtoupper", $names);
print_r($upper); // ["ALICE", "BOB", "CHARLIE"]
// Multiple arrays
$first = [1, 2, 3];
$second = [10, 20, 30];
$result = array_map(function($a, $b) {
return $a + $b;
}, $first, $second);
print_r($result); // [11, 22, 33]
?>
array_filter() - Filter Elements
Filter array elements using a callback:
<?php
// Filter even numbers
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
$even = array_filter($numbers, function($n) {
return $n % 2 === 0;
});
print_r($even); // [2, 4, 6, 8]
// Filter non-empty values
$data = ["apple", "", "banana", null, "cherry", 0];
$filtered = array_filter($data);
print_r($filtered); // ["apple", "banana", "cherry"]
// Filter with keys
$ages = ["John" => 25, "Jane" => 30, "Bob" => 17, "Alice" => 22];
$adults = array_filter($ages, function($age, $name) {
return $age >= 18;
}, ARRAY_FILTER_USE_BOTH);
print_r($adults);
?>
array_reduce() - Reduce to Single Value
Reduce array to a single value using a callback:
<?php
// Sum all numbers
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum; // 15
// Find maximum
$max = array_reduce($numbers, function($carry, $item) {
return $item > $carry ? $item : $carry;
}, $numbers[0]);
echo $max; // 5
// Concatenate strings
$words = ["Hello", "World", "PHP"];
$sentence = array_reduce($words, function($carry, $item) {
return $carry . " " . $item;
}, "");
echo trim($sentence); // "Hello World PHP"
?>
Tip:
array_map(), array_filter(), and array_reduce() are fundamental functional programming patterns. Master them for cleaner, more expressive code.
Array Searching Functions
in_array() - Check if Value Exists
<?php
$fruits = ["apple", "banana", "cherry"];
if (in_array("banana", $fruits)) {
echo "Found banana!";
}
// Strict type checking
$numbers = [1, 2, 3, "4"];
var_dump(in_array(4, $numbers)); // true (loose)
var_dump(in_array(4, $numbers, true)); // false (strict)
?>
array_search() - Find Key of Value
<?php
$colors = ["red", "green", "blue", "yellow"];
$key = array_search("blue", $colors);
echo $key; // 2
// Returns false if not found
$key = array_search("purple", $colors);
if ($key === false) {
echo "Color not found";
}
// With associative arrays
$ages = ["John" => 25, "Jane" => 30, "Bob" => 25];
$name = array_search(25, $ages);
echo $name; // "John" (first match)
?>
array_key_exists() vs isset()
<?php
$data = ["name" => "John", "age" => null];
// array_key_exists checks if key exists (even if value is null)
var_dump(array_key_exists("age", $data)); // true
var_dump(array_key_exists("email", $data)); // false
// isset returns false if value is null
var_dump(isset($data["age"])); // false
var_dump(isset($data["name"])); // true
?>
Warning: Use
array_search() with strict comparison (===) because it returns the key (which could be 0), not true/false.
Array Manipulation Functions
array_slice() - Extract Portion
<?php
$fruits = ["apple", "banana", "cherry", "date", "elderberry"];
// Get slice from position 1, length 3
$slice = array_slice($fruits, 1, 3);
print_r($slice); // ["banana", "cherry", "date"]
// Negative offset (from end)
$slice = array_slice($fruits, -2);
print_r($slice); // ["date", "elderberry"]
// Preserve keys
$slice = array_slice($fruits, 1, 3, true);
print_r($slice);
?>
array_splice() - Remove and Replace
<?php
$colors = ["red", "green", "blue", "yellow"];
// Remove 2 elements starting at index 1
$removed = array_splice($colors, 1, 2);
print_r($removed); // ["green", "blue"]
print_r($colors); // ["red", "yellow"]
// Remove and replace
$colors = ["red", "green", "blue", "yellow"];
array_splice($colors, 1, 2, ["orange", "purple"]);
print_r($colors); // ["red", "orange", "purple", "yellow"]
// Insert without removing
$colors = ["red", "blue"];
array_splice($colors, 1, 0, ["green"]);
print_r($colors); // ["red", "green", "blue"]
?>
array_merge() - Combine Arrays
<?php
// Merge indexed arrays
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$merged = array_merge($arr1, $arr2);
print_r($merged); // [1, 2, 3, 4, 5, 6]
// Merge associative arrays (later values override)
$default = ["color" => "red", "size" => "M"];
$custom = ["size" => "L", "style" => "casual"];
$config = array_merge($default, $custom);
print_r($config);
// ["color" => "red", "size" => "L", "style" => "casual"]
// Merge multiple arrays
$result = array_merge($arr1, $arr2, [7, 8, 9]);
print_r($result);
?>
Array Calculation Functions
<?php
$numbers = [10, 20, 30, 40, 50];
// Sum of all elements
echo array_sum($numbers); // 150
// Product of all elements
echo array_product($numbers); // 12000000
// Count elements
echo count($numbers); // 5
// Count element frequencies
$items = ["apple", "banana", "apple", "cherry", "banana", "apple"];
$counts = array_count_values($items);
print_r($counts);
// ["apple" => 3, "banana" => 2, "cherry" => 1]
?>
Array Sorting Functions
<?php
// Sort indexed array (values)
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
sort($numbers); // Ascending
print_r($numbers);
rsort($numbers); // Descending
print_r($numbers);
// Sort associative array (by value, maintain keys)
$ages = ["John" => 25, "Jane" => 30, "Bob" => 20];
asort($ages); // Ascending by value
print_r($ages);
arsort($ages); // Descending by value
print_r($ages);
// Sort associative array (by key)
ksort($ages); // Ascending by key
print_r($ages);
krsort($ages); // Descending by key
print_r($ages);
// Custom sorting with callback
$words = ["apple", "Banana", "cherry", "Date"];
usort($words, function($a, $b) {
return strcasecmp($a, $b); // Case-insensitive
});
print_r($words);
?>
Note: Sorting functions modify the original array and return true/false (not a sorted copy).
Array Combination Functions
<?php
// Combine two arrays as keys and values
$keys = ["name", "age", "city"];
$values = ["John", 25, "New York"];
$person = array_combine($keys, $values);
print_r($person);
// ["name" => "John", "age" => 25, "city" => "New York"]
// Chunk array into smaller arrays
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunks = array_chunk($numbers, 3);
print_r($chunks);
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// Fill array with values
$filled = array_fill(0, 5, "x");
print_r($filled); // ["x", "x", "x", "x", "x"]
// Fill with range of values
$range = range(1, 10, 2);
print_r($range); // [1, 3, 5, 7, 9]
?>
Array Unique and Difference Functions
<?php
// Remove duplicates
$numbers = [1, 2, 2, 3, 4, 4, 5];
$unique = array_unique($numbers);
print_r($unique); // [1, 2, 3, 4, 5]
// Find values in first array not in second
$arr1 = [1, 2, 3, 4, 5];
$arr2 = [3, 4, 5, 6, 7];
$diff = array_diff($arr1, $arr2);
print_r($diff); // [1, 2]
// Find common values
$intersect = array_intersect($arr1, $arr2);
print_r($intersect); // [3, 4, 5]
// Difference by keys
$a = ["a" => 1, "b" => 2, "c" => 3];
$b = ["b" => 2, "c" => 4, "d" => 5];
$diff = array_diff_key($a, $b);
print_r($diff); // ["a" => 1]
?>
Array Reversal and Shuffling
<?php
// Reverse array order
$colors = ["red", "green", "blue"];
$reversed = array_reverse($colors);
print_r($reversed); // ["blue", "green", "red"]
// Flip keys and values
$map = ["a" => 1, "b" => 2, "c" => 3];
$flipped = array_flip($map);
print_r($flipped); // [1 => "a", 2 => "b", 3 => "c"]
// Shuffle array (randomize order)
$deck = ["A", "K", "Q", "J", "10"];
shuffle($deck);
print_r($deck); // Random order
// Get random element(s)
$fruits = ["apple", "banana", "cherry", "date"];
$random = array_rand($fruits, 2);
print_r($random); // Two random keys
?>
Practical Example: Data Processing Pipeline
<?php
// Process user data
$users = [
["name" => "John Doe", "age" => 25, "active" => true],
["name" => "Jane Smith", "age" => 17, "active" => true],
["name" => "Bob Johnson", "age" => 35, "active" => false],
["name" => "Alice Brown", "age" => 28, "active" => true]
];
// Filter: Get active adult users
$activeAdults = array_filter($users, function($user) {
return $user["active"] && $user["age"] >= 18;
});
// Map: Extract names
$names = array_map(function($user) {
return $user["name"];
}, $activeAdults);
// Reduce: Create comma-separated list
$nameList = array_reduce($names, function($carry, $name) {
return $carry ? $carry . ", " . $name : $name;
}, "");
echo "Active adult users: $nameList";
// Output: Active adult users: John Doe, Alice Brown
?>
Practical Example: Shopping Cart Operations
<?php
$cart = [
["id" => 1, "name" => "Laptop", "price" => 999, "qty" => 1],
["id" => 2, "name" => "Mouse", "price" => 25, "qty" => 2],
["id" => 3, "name" => "Keyboard", "price" => 75, "qty" => 1]
];
// Calculate subtotals
$cartWithSubtotals = array_map(function($item) {
$item["subtotal"] = $item["price"] * $item["qty"];
return $item;
}, $cart);
// Calculate total
$total = array_reduce($cartWithSubtotals, function($sum, $item) {
return $sum + $item["subtotal"];
}, 0);
echo "Cart Total: $$total"; // Cart Total: $1124
// Find specific item
$itemKey = array_search(2, array_column($cart, "id"));
if ($itemKey !== false) {
echo "Found: " . $cart[$itemKey]["name"];
}
// Sort by price
usort($cart, function($a, $b) {
return $a["price"] - $b["price"];
});
?>
Exercise:
- Create an array of numbers and use array functions to:
- Filter only even numbers
- Square each number
- Calculate the sum of all squared even numbers
- Create an array of students with name, grade, and subject. Write code to:
- Filter students with grades above 80
- Sort them by grade descending
- Extract only their names
- Create two arrays and find their union, intersection, and difference
- Write a function that removes duplicate values from a nested array
Performance Tips
- Use
isset()instead ofarray_key_exists()when null values aren't important (it's faster) - Use
array_map()instead of foreach loops when transforming all elements - Avoid
array_merge()in loops; usearray_push()or[]instead - Use
array_column()to extract a single column from multi-dimensional arrays - Chain array functions for cleaner, more readable code
Tip: Learn to think functionally with
array_map(), array_filter(), and array_reduce(). They often lead to cleaner, more maintainable code than traditional loops.
Common Patterns
<?php
// Extract column from 2D array
$users = [
["name" => "John", "email" => "john@example.com"],
["name" => "Jane", "email" => "jane@example.com"]
];
$emails = array_column($users, "email");
// Pluck with keys
$emailMap = array_column($users, "email", "name");
print_r($emailMap);
// ["John" => "john@example.com", "Jane" => "jane@example.com"]
// Group by key
$items = [
["category" => "fruit", "name" => "apple"],
["category" => "fruit", "name" => "banana"],
["category" => "veggie", "name" => "carrot"]
];
$grouped = [];
foreach ($items as $item) {
$grouped[$item["category"]][] = $item["name"];
}
print_r($grouped);
?>
Summary
In this lesson, you learned:
- Transformation functions:
array_map(),array_filter(),array_reduce() - Search functions:
in_array(),array_search(),array_key_exists() - Manipulation functions:
array_slice(),array_splice(),array_merge() - Calculation functions:
array_sum(),array_product(),count() - Set operations:
array_unique(),array_diff(),array_intersect() - Practical applications in data processing and business logic
Mastering array functions is essential for writing efficient, clean PHP code. Practice combining them to solve complex problems elegantly!