Array Creation and Access
Indexed Arrays
<?php
// Create indexed array
$products = ['Widget', 'Gadget', 'Doohickey'];
echo $products[0]; // 'Widget'
echo $products[1]; // 'Gadget'
echo count($products); // 3
// Add elements
$products[] = 'Thingamajig'; // Append to end
array_push($products, 'Whatchamacallit'); // Another way to append
array_unshift($products, 'First'); // Add to beginning
// Remove elements
$last = array_pop($products); // Remove from end
$first = array_shift($products); // Remove from beginning
unset($products[1]); // Remove by index
// Check if key exists
if (array_key_exists(0, $products)) {
echo 'Key 0 exists';
}
// Check if value exists
if (in_array('Widget', $products)) {
echo 'Widget found';
}
Associative Arrays
<?php
// Create associative array
$product = [
'id' => 1,
'name' => 'Widget Pro',
'price' => 29.99,
'sku' => 'WDG-001',
'stock' => 150,
'active' => true
];
echo $product['name']; // 'Widget Pro'
echo $product['price']; // 29.99
// Add/update elements
$product['weight'] = 0.5; // Add new key
$product['price'] = 24.99; // Update existing
// Remove elements
unset($product['weight']);
// Iterate over associative array
foreach ($product as $key => $value) {
echo "$key: $value\n";
}
// Get all keys and values
$keys = array_keys($product); // ['id', 'name', 'price', ...]
$values = array_values($product); // [1, 'Widget Pro', 29.99, ...]
Multidimensional Arrays
<?php
// Nested associative arrays (common in Magento)
$catalog = [
'categories' => [
'electronics' => [
'name' => 'Electronics',
'products' => [
[
'id' => 1,
'name' => 'Phone',
'price' => 599.99
],
[
'id' => 2,
'name' => 'Laptop',
'price' => 999.99
]
]
],
'clothing' => [
'name' => 'Clothing',
'products' => []
]
]
];
// Access nested values
echo $catalog['categories']['electronics']['products'][0]['name']; // 'Phone'
// Safely access nested values
$firstProduct = $catalog['categories']['electronics']['products'][0] ?? null;
$phonePrice = $firstProduct['price'] ?? 0.0;
Array Operators
<?php
// Union operator (+)
$defaults = ['color' => 'red', 'size' => 'medium', 'qty' => 1];
$custom = ['color' => 'blue', 'qty' => 5];
$result = $defaults + $custom;
// ['color' => 'red', 'size' => 'medium', 'qty' => 1]
// Note: + doesn't override existing keys!
// Merge operator (array_merge)
$result = array_merge($defaults, $custom);
// ['color' => 'blue', 'size' => 'medium', 'qty' => 5]
// array_merge DOES override existing keys
// Equality comparison
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 2, 'a' => 1];
echo $a == $b; // true (same values, order doesn't matter)
echo $a === $b; // false (different order)
echo $a == $b; // true for ==
Key Takeaway
Arrays in PHP are ordered maps that can be indexed or associative. Magento uses arrays extensively for configuration, product data, and form handling. Always use ?? for safe nested array access.
Essential Array Functions
array_map - Transform Each Element
<?php
$prices = [10.99, 24.99, 49.99, 99.99];
// Double each price
$doubled = array_map(fn($p) => $p * 2, $prices);
// [21.98, 49.98, 99.98, 199.98]
// Format prices
$formatted = array_map(fn($p) => '\$' . number_format($p, 2), $prices);
// ['$10.99', '$24.99', '$49.99', '$99.99']
// Transform associative array
$products = [
['name' => 'Widget', 'price' => 29.99],
['name' => 'Gadget', 'price' => 49.99]
];
$productNames = array_map(fn($p) => $p['name'], $products);
// ['Widget', 'Gadget']
// Add computed field to each item
$enriched = array_map(function ($product) {
$product['formatted_price'] = '\$' . number_format($product['price'], 2);
$product['is_expensive'] = $product['price'] > 50;
return $product;
}, $products);
array_filter - Keep Matching Elements
<?php
$products = [
['name' => 'Widget', 'price' => 29.99, 'active' => true],
['name' => 'Gadget', 'price' => 49.99, 'active' => false],
['name' => 'Doohickey', 'price' => 19.99, 'active' => true],
['name' => 'Thingamajig', 'price' => 79.99, 'active' => true]
];
// Filter by single condition
$active = array_filter($products, fn($p) => $p['active']);
// Filter by multiple conditions
$cheapActive = array_filter($products, fn($p) =>
$p['active'] && $p['price'] < 50
);
// Filter with key access
$filtered = array_filter($products, function ($p, $key) {
return $p['price'] > 30 && strlen($key) > 0;
}, ARRAY_FILTER_USE_BOTH);
// Remove falsy values from flat array
$values = [0, 1, '', 'hello', null, false, 42];
$clean = array_filter($values); // [1, 'hello', 42]
// Preserving keys
$indexed = array_filter($products, fn($p) => $p['active'], ARRAY_FILTER_USE_KEY);
array_reduce - Accumulate to Single Value
<?php
$prices = [10.99, 24.99, 49.99, 99.99];
// Sum all prices
$total = array_reduce($prices, fn($carry, $price) => $carry + $price, 0);
// 185.96
// Find most expensive product
$mostExpensive = array_reduce($products, function ($carry, $product) {
return ($carry === null || $product['price'] > $carry['price'])
? $product
: $carry;
}, null);
// Group products by category
$grouped = array_reduce($products, function ($carry, $product) {
$category = $product['category'] ?? 'uncategorized';
$carry[$category][] = $product;
return $carry;
}, []);
// Build a lookup table
$lookup = array_reduce($products, function ($carry, $product) {
$carry[$product['id']] = $product;
return $carry;
}, []);
Other Essential Functions
<?php
$products = [
['id' => 1, 'name' => 'Widget', 'price' => 29.99, 'category' => 'tools'],
['id' => 2, 'name' => 'Gadget', 'price' => 49.99, 'category' => 'electronics'],
['id' => 3, 'name' => 'Hammer', 'price' => 15.99, 'category' => 'tools'],
];
// array_column - Extract single column
$names = array_column($products, 'name');
// ['Widget', 'Gadget', 'Hammer']
// array_column with key
$lookup = array_column($products, null, 'id');
// [1 => ['id' => 1, ...], 2 => [...], 3 => [...]]
// array_merge - Combine arrays
$defaults = ['color' => 'red', 'size' => 'M'];
$custom = ['color' => 'blue', 'weight' => 0.5];
$merged = array_merge($defaults, $custom);
// ['color' => 'blue', 'size' => 'M', 'weight' => 0.5]
// array_combine - Keys from one array, values from another
$keys = ['name', 'price', 'sku'];
$values = ['Widget', 29.99, 'WDG-001'];
$product = array_combine($keys, $values);
// ['name' => 'Widget', 'price' => 29.99, 'sku' => 'WDG-001']
// array_unique - Remove duplicates
$colors = ['red', 'blue', 'red', 'green', 'blue'];
$unique = array_unique($colors); // ['red', 'blue', 'green']
// array_flip - Swap keys and values
$prices = ['widget' => 29.99, 'gadget' => 49.99];
$lookup = array_flip($prices);
// [29.99 => 'widget', 49.99 => 'gadget']
// array_slice - Get portion of array
$page = array_slice($products, 0, 2); // First 2 items
$page2 = array_slice($products, 2, 2); // Items 3-4
// array_splice - Remove/replace portion
$items = [1, 2, 3, 4, 5];
array_splice($items, 1, 2); // Remove items at index 1-2
// $items is now [1, 4, 5]
// array_walk - Apply function to each element
array_walk($products, function (&$product, $key) {
$product['formatted_price'] = '\$' . number_format($product['price'], 2);
});
Key Takeaway
array_map transforms elements, array_filter keeps matching elements, array_reduce accumulates to a single value, and array_column extracts a single property from nested arrays. These are the most commonly used array functions in Magento.
Arrays in Magento
Magento Array Usage
Magento uses arrays extensively for:
- Configuration data
- Product attributes
- Form data
- API responses
- Database results
Configuration Arrays
<?php
// Magento module configuration (from di.xml)
$config = [
'Vendor\\Module\\Helper\\Data' => [
'arguments' => [
'cacheManager' => [
'instance' => 'Magento\\Framework\\App\\Cache\\Manager',
],
'config' => [
'instance' => 'Magento\\Framework\\Config\\Data',
]
]
]
];
// Processing configuration
foreach ($config as $className => $classConfig) {
$args = $classConfig['arguments'] ?? [];
foreach ($args as $argName => $argConfig) {
$instance = $argConfig['instance'] ?? null;
if ($instance) {
// Register for dependency injection
}
}
}
Product Data Arrays
<?php
// Typical Magento product data structure
$productData = [
'id' => 123,
'sku' => 'WDG-001',
'name' => 'Widget Pro',
'price' => '29.9900', // String from database!
'status' => 1, // 1=enabled, 2=disabled
'visibility' => 4, // 4=catalog+search
'type_id' => 'simple', // simple, configurable, bundle
'attribute_set_id' => 4,
'category_ids' => [3, 7, 12],
'custom_attributes' => [
[
'attribute_code' => 'description',
'value' => '<p>Product description</p>'
],
[
'attribute_code' => 'short_description',
'value' => '<p>Short description</p>'
]
]
];
// Extract attributes by code
$attributes = array_column($productData['custom_attributes'], 'value', 'attribute_code');
$description = $attributes['description'] ?? '';
// Filter enabled products only
$enabledProducts = array_filter($products, fn($p) => $p['status'] === 1);
// Sort by price
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
Form Data Processing
<?php
// Process submitted form data
$rawData = $_POST;
// Clean and validate
$cleanData = array_filter($rawData, function ($value) {
return !empty(trim($value));
});
// Map form fields to database columns
$mapping = [
'product_name' => 'name',
'product_price' => 'price',
'product_sku' => 'sku',
'product_description' => 'description'
];
$mappedData = [];
foreach ($mapping as $formField => $dbColumn) {
if (isset($cleanData[$formField])) {
$mappedData[$dbColumn] = $cleanData[$formField];
}
}
// Add computed fields
$mappedData['created_at'] = date('Y-m-d H:i:s');
$mappedData['updated_at'] = date('Y-m-d H:i:s');
Advanced Array Patterns
<?php
// Flatten multidimensional array
function flattenArray(array $array): array
{
$result = [];
array_walk_recursive($array, function ($value) use (&$result) {
$result[] = $value;
});
return $result;
}
$nested = [[1, 2], [3, 4], [5, 6]];
$flat = flattenArray($nested); // [1, 2, 3, 4, 5, 6]
// Chunk array for pagination
$allProducts = range(1, 50);
$pages = array_chunk($allProducts, 10);
// [[1..10], [11..20], [21..30], [31..40], [41..50]]
// Array partition (split by condition)
function partition(array $array, callable $predicate): array
{
$result = [[], []];
foreach ($array as $key => $value) {
$result[(int)$predicate($value, $key)][] = $value;
}
return $result;
}
$prices = [10, 25, 50, 75, 100];
[$cheap, $expensive] = partition($prices, fn($p) => $p > 30);
// $cheap = [10, 25], $expensive = [50, 75, 100]
Key Takeaway
Magento uses arrays for almost everything: configuration, product data, form data, and API responses. Master array_map, array_filter, array_reduce, and array_column to work with Magento data effectively.
Quiz
1. What does array_map() do?
2. What is the difference between array_merge and the + operator?
3. How do you extract a single column from a multidimensional array?
4. What is the initial value parameter in array_reduce()?
5. How does Magento typically store price values in arrays?
Flashcards
Question
What does array_map do?
Click to reveal answer
Answer
Transforms each element using a callback function and returns a new array. Example: array_map(fn($x) => $x * 2, [1,2,3]) returns [2,4,6].
Question
What does array_filter do?
Click to reveal answer
Answer
Keeps elements that pass a test. Example: array_filter($arr, fn($x) => $x > 10) keeps values greater than 10.
Question
What does array_reduce do?
Click to reveal answer
Answer
Accumulates array to a single value using a callback. Example: array_reduce([1,2,3], fn($carry, $x) => $carry + $x, 0) returns 6.
Question
What does array_column do?
Click to reveal answer
Answer
Extracts a single column from a multidimensional array. Example: array_column($products, 'name') returns ['Widget', 'Gadget'].
Question
What is the difference between array_merge and + operator?
Click to reveal answer
Answer
array_merge: overrides duplicate keys. + operator: keeps first array's values for duplicates.
Question
How do you safely access nested array values?
Click to reveal answer
Answer
Use null coalescing: $value = $array['key1']['key2'] ?? null. This prevents undefined index warnings.
Question
What does array_chunk do?
Click to reveal answer
Answer
Splits an array into smaller chunks of specified size. Useful for pagination: array_chunk($products, 10) gives arrays of 10 items each.
Question
What does array_column with 3 parameters do?
Click to reveal answer
Answer
array_column($arr, null, 'key') uses 'key' column as the array key instead of numeric index. Creates a lookup table.
Revision Notes
Key Takeaways
- 1. PHP arrays are ordered maps supporting both indexed and associative keys
- 2. array_map transforms each element, array_filter keeps matching elements
- 3. array_reduce accumulates to a single value
- 4. array_column extracts a specific column from multidimensional arrays
- 5. array_merge combines arrays (overrides duplicate keys), + operator doesn't
- 6. Magento stores prices as strings - cast to float for calculations
- 7. Use ?? (null coalescing) for safe nested array access
Interview Tips
- • Explain the difference between array_map, array_filter, and array_reduce
- • Know when to use array_column vs array_map for column extraction
- • Describe how Magento uses arrays for configuration and product data
- • Understand the difference between array_merge and the + operator
- • Be able to chain array functions for complex data transformations
Cheat Sheet
PHP Array Functions Cheat Sheet
Transform:
array_map(fn($x) => $x * 2, $arr) // Transform each
Filter:
array_filter($arr, fn($x) => $x > 10) // Keep matching
Accumulate:
array_reduce($arr, fn($carry, $x) => $carry + $x, 0) // Sum
Extract:
array_column($products, 'name') // Get names
array_column($products, null, 'id') // Lookup by id
Combine:
array_merge($a, $b) // Merge (overrides)
$a + $b // Union (no override)
array_combine($keys, $values) // Keys+values
Other:
array_keys($arr) // All keys
array_values($arr) // All values
array_unique($arr) // Remove duplicates
array_chunk($arr, 10) // Split into chunks
array_slice($arr, 0, 10) // Get portion
in_array($val, $arr) // Check if value exists
array_key_exists($key, $arr) // Check if key exists