Cart Line Merge Review
Reviews cart lines and merges compatible SKU, option, and price records without losing quantity detail.
Purpose
Reviews cart lines and merges compatible SKU, option, and price records without losing quantity detail.
Snippet details
ContextEcommerceLevelAdvancedCopy-and-paste statusMarked safe after review.Categories
- Security
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Cart Line Merge Review.
*
* Purpose:
* Reviews cart lines and merges compatible SKU, option, and price records without losing quantity detail.
*
* @param array $cart_lines Cart line rows.
* @return array Merged cart lines.
*/
function ogSnippetCartLineMergeReview(array $cart_lines): array {
$merged = array();
foreach ($cart_lines as $line) {
$key_parts = array((string) $line['sku'], (string) $line['option_hash'], (string) $line['unit_cents']);
$key = implode('|', $key_parts);
if (!isset($merged[$key])) {
$merged[$key] = $line;
$merged[$key]['quantity'] = 0;
}
$merged[$key]['quantity'] += (int) $line['quantity'];
}
return array_values($merged);
}
$cart_lines = array(array('sku' => 'BLASTER-HOLSTER', 'option_hash' => 'left', 'unit_cents' => 2400, 'quantity' => 1), array('sku' => 'BLASTER-HOLSTER', 'option_hash' => 'left', 'unit_cents' => 2400, 'quantity' => 2));
$merged_lines = ogSnippetCartLineMergeReview($cart_lines);
echo $merged_lines[0]['quantity'];