Arrays in PHP

7 questions found

What is an array in PHP and what types of arrays does PHP support?

Beginner
An array in PHP is a data structure that lets you store multiple values in a single variable, and PHP supports indexed arrays where elements are accessed by a numeric position, associative arrays where elements are accessed by a named key, and multidimensional arrays which are arrays containing other arrays, giving you a flexible way to organize related data together.
$fruits = ['apple', 'banana', 'cherry'];
$person = ['name' => 'Ali', 'age' => 30];
Real-world example An online store stores a customer's shopping cart items as an indexed array, while storing the customer's profile details, such as name and email, as an associative array for easy lookup by field name.

Common follow-ups: What is the difference between an indexed array and an associative array?;How do you create a multidimensional array in PHP?

Strings & String Functions;Functions & Scope

How do you add, remove, and access elements within a PHP array?

Beginner
You can add an element to the end of an array using square bracket syntax or the array_push function, remove an element using unset for a specific key or array_pop to remove the last element, and access an element directly by referencing its index or key inside square brackets, giving you full control over the contents of an array as your program runs.
$colors = ['red', 'green'];
$colors[] = 'blue';
unset($colors[0]);
echo $colors[1];
Real-world example A task management application adds a new task to a list by appending it to an array, and removes a completed task by unsetting its specific key, keeping the array always reflecting the current active tasks.

Common follow-ups: What is the difference between unset and array_splice for removing elements?;How do you check if a specific key exists in an array?

Functions & Scope;Basics & Types

How do array_map, array_filter, and array_reduce help you transform and process array data without writing manual loops?

Intermediate
array_map applies a given function to every element of an array and returns a new array with the transformed values, array_filter returns a new array containing only the elements that pass a given test function, and array_reduce combines all elements of an array into a single value by repeatedly applying a function, together letting you express common data transformations concisely and clearly instead of writing verbose manual foreach loops.
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
Real-world example An order processing system uses array_map to convert a list of product prices into their tax inclusive totals, and array_reduce to calculate the grand total of an entire shopping cart in a single clear expression.

Common follow-ups: What is the performance difference between array_map and a manual foreach loop?;Can array_filter preserve the original array keys?

Closures & Anonymous Functions;Functions & Scope

How do you sort arrays in PHP, and what is the difference between functions like sort, asort, and usort?

Intermediate
The sort function reorders an array by value and reindexes the keys numerically, asort sorts an array by value while preserving the original keys, which is useful for associative arrays, and usort lets you define a completely custom comparison function to sort elements based on any logic you need, such as sorting an array of objects by a specific property.
$scores = ['Ali' => 85, 'Sara' => 92, 'Omar' => 78];
asort($scores);

$products = [['name' => 'Pen', 'price' => 5], ['name' => 'Book', 'price' => 20]];
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
Real-world example An e commerce catalog uses usort with a custom comparison function to sort a list of products by price, letting customers view items from cheapest to most expensive.

Common follow-ups: What does the spaceship operator do in a usort comparison function?;How do you sort an array in descending order?

Functions & Scope;OOP

What is array destructuring in PHP, and how does the list function or short array syntax simplify extracting values from an array?

Intermediate
Array destructuring lets you assign multiple array elements directly to individual variables in a single statement, using either the list function or the equivalent shorthand square bracket syntax, which is especially convenient when a function returns multiple related values as an array and you want to immediately assign each value to its own clearly named variable.
[$name, $age] = ['Ali', 30];
echo "$name is $age years old";
Real-world example A function that calculates both the width and height of an image returns them as an array, and the calling code immediately destructures that array into two clearly named variables for easy use afterward.

Common follow-ups: Can you skip specific elements when destructuring an array?;Does destructuring work with associative arrays as well as indexed arrays?

Functions & Scope;PHP 8 Features (Attributes Enums Match Nullsafe Operator)

How do you merge, combine, and compare arrays in PHP, and what are the subtle differences between array_merge and the plus operator?

Advanced
array_merge combines two or more arrays, and for string keys, later values overwrite earlier ones while numeric keys are renumbered sequentially, whereas the plus operator also combines arrays but keeps the first array's values for any keys that exist in both, including numeric keys, without any renumbering, meaning the two approaches can produce noticeably different results, especially when merging indexed arrays.
$a = [1, 2, 3];
$b = [4, 5, 6];
print_r(array_merge($a, $b));
print_r($a + $b);
Real-world example A configuration system merges a set of default settings with user provided overrides using the plus operator specifically because it wants the user's values to only fill in missing keys rather than overwrite already defined ones.

Common follow-ups: How do array_diff and array_intersect help compare two arrays?;What happens when array_merge combines two arrays that both have numeric keys?

OOP;Design Patterns in PHP

How does PHP handle array copying behavior, and when do arrays actually get passed by reference instead of by value?

Advanced
PHP arrays are value types by default, meaning assigning an array to a new variable or passing it into a function creates an independent copy, so changes to the copy do not affect the original, but you can explicitly pass an array by reference using an ampersand in a function's parameter definition, meaning changes made inside that function directly affect the original array passed in, which is an important distinction to understand to avoid unexpected bugs.
function addItem(array &$cart, string $item) {
    $cart[] = $item;
}
$cart = ['apple'];
addItem($cart, 'banana');
print_r($cart);
Real-world example A shopping cart function is intentionally designed to accept the cart array by reference, so that adding an item inside the function directly updates the original cart variable used elsewhere in the application, avoiding the need to return and reassign the array manually.

Common follow-ups: What are the performance implications of passing large arrays by value versus by reference?;How does this copy on write behavior actually work internally in PHP?

Functions & Scope;Performance Optimization & OPcache