3 - array functions in php

Preview
1 min
7 min read

Short description: Hands-on, business-focused walkthrough of PHP's most useful array functions. Learn how to manipulate data arrays for real-life use cases like shopping carts, CSV imports, reporting and analytics.

Why arrays matter for real-world apps

Arrays are the backbone of many PHP programs. In real businesses you will use arrays to:

  • Store shopping cart items and calculate order totals.
  • Transform CSV / Excel import rows to database rows.
  • Aggregate analytics (counts, sums, averages) for dashboards.
  • Filter and clean user-submitted data before inserting to DB.

This lesson covers built-in PHP functions that make these tasks simple, fast and readable.

Canonical example (starting code)

Below is a clean version of the example you provided, then we'll break it down and extend it for business use cases.

<?php


// Built-in array functions example

$numbers = [1, 2, 3, 4, 5, 25];
$letters = ["hello", "a", "b", "c"];

// Safe search: array_search returns index or false
$index = array_search("hello", $letters, true);
if ($index !== false) {
echo "Found 'hello' at index: {$index}\n";
}

// Count and sum
echo "Count: " . count($letters) . "\n";
echo "Sum: " . array_sum($numbers) . "\n";

// Add and remove
array_push($numbers, 6); // add to end
array_pop($numbers); // remove last
array_unshift($letters, "z"); // add to start
array_shift($letters); // remove first

// Merge arrays
$merged = array_merge($numbers, $letters);

// Filter and map
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$squared = array_map(fn($n) => $n * $n, $numbers);

echo "
";
print_r($letters);
print_r($merged);
print_r($even);
print_r($squared);
echo "
"; ?>

Core array functions — what they do & business examples

count()

Returns the number of elements. Useful for showing cart item counts or batch sizes before processing.

// e-commerce: show cart item count


$cart = ['sku_1', 'sku_2', 'sku_3'];
echo "Items in cart: " . count($cart);

array_sum()

Sum numeric values. Use it to total prices, invoice line totals or numeric analytics.

$prices = [19.99, 5.00, 3.50];


$total = array_sum($prices); // 28.49

in_array() / array_search()

in_array checks presence, array_search returns the index. Always use strict mode (true) when types matter.

// check whether SKU exists


if (in_array('SKU123', $inventory, true)) {
// handle found
}

array_push(), array_pop(), array_unshift(), array_shift()

Push/pop for stack-like operations and unshift/shift for queue-like operations. Useful when implementing simple FIFO/ LIFO buffers or modifying lists before saving.

sort(), rsort(), asort(), arsort(), usort()

Sorting functions: sort reindexes, asort preserves keys. For complex sorting use usort with a comparator. Example: sort product list by popularity or price.

array_merge()

Combine arrays — handy when merging two data sources, e.g., default settings + user settings. Be careful with numeric keys (they get reindexed).

array_filter()

Keep only elements matching a condition. Great for removing invalid rows after processing CSV input.

// remove empty rows from CSV import


$rows = array_filter($rows, fn($r) => !empty(array_filter($r)));

array_map()

Transform each element. Use it to cast data types, format dates, or compute derived values.

array_reduce()

Reduce an array to a single value — e.g., compute totals with custom logic (discount rules, tax calculations).

$subtotal = array_reduce($items, function($carry, $item) {
return $carry + ($item['price'] * $item['qty']);


}, 0);

array_column()

Extract a single column from a multidimensional array — perfect to get all emails or IDs from query results before a batch operation.

array_unique()

Remove duplicates — useful for lists of tags, emails, or identifiers before bulk inserts to avoid duplicates.

array_slice(), array_splice()

Pick a segment of an array or delete/replace a segment — useful for pagination logic when you already have arrays in memory.

Business-focused examples

Example 1 — Shopping cart totals & discounts

// items from cart (after DB lookup or session)


$cartItems = [
['sku' => 'A1', 'price' => 20.0, 'qty' => 2],
['sku' => 'B2', 'price' => 10.0, 'qty' => 1],
];

// compute subtotal using array_reduce
$subtotal = array_reduce($cartItems, function($carry, $item) {
return $carry + ($item['price'] * $item['qty']);
}, 0);

// apply a percentage discount if subtotal >= 50
$discount = ($subtotal >= 50) ? $subtotal * 0.1 : 0;

$grandTotal = $subtotal - $discount;
echo "Subtotal: {$subtotal}, Discount: {$discount}, Total: {$grandTotal}";

Example 2 — Clean CSV import before DB insert

// assume $csvRows is an array of associative arrays from fgetcsv


$cleanRows = array_filter($csvRows, function($row) {
// drop rows with missing mandatory fields
return !empty($row['email']) && !empty($row['name']);
});

// normalize emails and remove duplicates
$emails = array_map(fn($r) => strtolower(trim($r['email'])), $cleanRows);
$emails = array_unique($emails);

// now bulk-insert only new emails (use DB check via PDO)

Example 3 — Aggregation for dashboards

// prepare daily sales totals from orders array


$orders = [
['date' => '2025-11-01', 'total' => 120],
['date' => '2025-11-01', 'total' => 30],
['date' => '2025-11-02', 'total' => 40],
];

$grouped = [];
foreach ($orders as $o) {
$grouped[$o['date']] = ($grouped[$o['date']] ?? 0) + $o['total'];
}

// $grouped now contains totals per date for charts

Common pitfalls & best practices

  • Strict checks: Use strict mode for in_array and array_search when comparing types.
  • Numeric keys: array_merge reindexes numeric keys — use + (union) operator for preserving keys when appropriate.
  • Large arrays & memory: If data is huge (CSV with millions of rows), stream processing with generators or chunked DB inserts is better than loading everything into arrays.
  • Preserve keys: Use asort/arsort when you need to keep association between keys and values.
  • Use native functions: Native array functions are implemented in C and much faster than manual loops in PHP for most operations.

Performance note

Most array functions are highly optimized. However:

  • Avoid copying very large arrays repeatedly — many functions return new arrays. Use references and streaming where possible.
  • For numeric-heavy transforms consider benchmarking array_map vs. a simple loop if you need micro-optimizations.

Exercises (practice)

  1. Write a function that removes duplicate products in a cart by SKU and sums quantities for duplicates.
  2. Given an array of orders, produce top 5 selling SKUs (use array_count_values and arsort).
  3. Implement a CSV reader that yields rows using a generator and uses array_filter to drop invalid rows.

FAQ

Q: When should I use array_map vs a foreach loop?

A: Use array_map when you want a concise transformation returning a new array. If you need to operate on keys or perform side-effects (DB calls), a foreach loop is clearer.

Q: How to remove an element by value?

A: Use array_search to find the key, then unset($arr[$key]) to remove it.

Q: Are arrays suitable for large datasets?

A: For very large datasets, use streaming approaches (generators) or process data in chunks to avoid exhausting memory.

Summary checklist

  • Learn count, array_sum, in_array, array_search.
  • Practice transformations with array_map and filters with array_filter.
  • Use array_reduce for custom aggregations (totals, derived metrics).
  • Be aware of performance and memory when working with big arrays.

Related lessons & next steps

Recommended next lessons: 4 — Associative arrays & multidimensional arrays, 5 — Working with CSV & JSON in PHP, 6 — PDO: batch insert and transactions.

Author tip: when publishing to your CMS, add structured data and the following SEO keywords in your tags: PHP array functions, PHP arrays, array_map, array_filter, array_reduce, PHP shopping cart, PHP CSV import.

PHP & OOP & MySQLi & PDO

PHP & OOP & MySQLi & PDO

php website
softwarePHPWeb Development Basics
View course

Course Lessons