PHP Arrays · Chapter 8.4 · Count, Math & Set Operations

PHP Array Functions
count · sum · diff · intersect · chunk · combine

PHP Array Math और Set Operation Functions — counting, calculations, comparing arrays, splitting into chunks, और combining। Real world examples के साथ।

🔢 count/sum/product ➖ array_diff ∩ array_intersect ✂️ array_chunk 🔗 array_combine
countElements गिनना
diffA में है, B में नहीं
Intersect = Common values
chunkPages में divide करो

📋 इस Article में क्या-क्या है

  1. count() — Elements Count
  2. array_sum() / array_product()
  3. min() / max() in Arrays
  4. array_diff() — Difference
  5. array_intersect() — Common Values
  6. array_chunk() — Pages में तोड़ना
  7. array_combine() — Keys + Values
  8. array_pad() — Padding
1
count() — Elements Count करना
cnt
()

count() / sizeof()

Array में कितने elements हैं — यह count करता है। Multidimensional arrays में recursive count भी। sizeof() इसका alias है।

PHP 4+ Returns: int Most Used
int count( Countable|array $array, int $mode = COUNT_NORMAL )
count() — BASIC TO ADVANCED
<?php
// Basic count
$fruits = ["Apple", "Mango", "Banana"];
echo count($fruits); // 3
echo sizeof($fruits); // 3 (alias)

// Empty checks
echo count([]); // 0
echo count(null); // 0

// COUNT_RECURSIVE — nested arrays भी count
$students = [
  ["Rahul", "Priya"],
  ["Amit", "Neha", "Raj"],
];
echo count($students); // 2 (outer arrays)
echo count($students, COUNT_RECURSIVE); // 7 (2 + 5 inner)

// Real world — pagination
$products = range(1, 47); // 47 products
$perPage = 10;
$totalPages = ceil(count($products) / $perPage);
echo "Total Pages: $totalPages"; // 5
?>
💡 empty() vs count(): empty($arr) array खाली है? — true/false। count($arr) === 0 same काम। Performance के लिए empty() faster है।

2
array_sum() · array_product() · min() · max()
∑ ∏
min max

Array Math Functions

Array के numbers पर mathematical operations — sum (जोड़), product (गुणा), min (सबसे छोटा), max (सबसे बड़ा)।

PHP 4+ Numeric Arrays E-commerce Essential
MATH FUNCTIONS — EXAMPLES
<?php
$prices = [450, 799, 299, 199, 650];

// array_sum — total जोड़
echo array_sum($prices); // 2397

// array_product — सब गुणा
$factors = [2, 3, 4];
echo array_product($factors); // 24 (2×3×4)

// min() — सबसे छोटा
echo min($prices); // 199
echo min(5, 2, 8, 1); // 1 (direct values भी)

// max() — सबसे बड़ा
echo max($prices); // 799
echo max(5, 2, 8, 1); // 8

// Average (average PHP में built-in नहीं)
$avg = array_sum($prices) / count($prices);
echo round($avg, 2); // 479.40
?>
MATH — REAL WORLD: Cart Calculations
<?php
$cart = [
  ["name" => "PHP Book", "price" => 450, "qty" => 2],
  ["name" => "Laravel", "price" => 799, "qty" => 1],
  ["name" => "MySQL Notes", "price" => 299, "qty" => 3],
];

$lineTotal = array_map(fn($i) => $i["price"] * $i["qty"], $cart);
$subtotal = array_sum($lineTotal); // 2594
$gst = $subtotal * 0.18;
$total = $subtotal + $gst;

$allPrices = array_map(fn($i) => $i["price"], $cart);
echo "Cheapest: ₹" . min($allPrices); // ₹299
echo "Costliest: ₹" . max($allPrices); // ₹799
echo "Subtotal: ₹" . number_format($subtotal, 2); // ₹2,594.00
echo "Total: ₹" . number_format($total, 2); // ₹3,060.92
?>

3
array_diff() — Arrays में अंतर निकालना
diff
()

array_diff() / array_diff_key()

पहले array में वो values जो दूसरे में नहीं हैं — return करता है। Set theory में A - B जैसा। Permissions compare, missing items ढूँढने के लिए।

PHP 4+ Returns: array Keys Preserved
Array A [1, 2, 3, 4, 5]
Array B [3, 4, 5, 6, 7]
=
array_diff(A, B) [1, 2]
array array_diff( array $array, array ...$arrays )
array_diff() — EXAMPLES
<?php
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];

// A में है, B में नहीं
print_r(array_diff($a, $b)); // [1, 2]

// B में है, A में नहीं
print_r(array_diff($b, $a)); // [6, 7]

// Multiple arrays diff
$c = [1, 8];
print_r(array_diff($a, $b, $c)); // [2] — 1 is in $c too

// array_diff_key — keys से compare
$user1 = ["naam" => "Rahul", "age" => 25, "city" => "Delhi"];
$user2 = ["naam" => "Priya", "age" => 22];
print_r(array_diff_key($user1, $user2));
// ["city"=>"Delhi"] — user1 में है, user2 में key नहीं
?>
array_diff() — REAL WORLD EXAMPLES
<?php
// 1. Missing required fields check
$required = ["naam", "email", "phone", "city"];
$submitted = ["naam", "email"];
$missing = array_diff($required, $submitted);
if (!empty($missing)) {
  echo "Missing: " . implode(", ", $missing);
  // Missing: phone, city
}

// 2. New features in update
$oldFeatures = ["login", "register", "profile"];
$newFeatures = ["login", "register", "profile", "dashboard", "reports"];
$added = array_diff($newFeatures, $oldFeatures);
echo "New features: " . implode(", ", $added);
// New features: dashboard, reports
?>

4
array_intersect() — Common Values निकालना

intr

array_intersect() / array_intersect_key()

दोनों arrays में जो values common हैं — वो return करता है। Set theory में A ∩ B। Common permissions, shared interests ढूँढना।

PHP 4+ Returns: array Keys from first array
Array A [1, 2, 3, 4, 5]
Array B [3, 4, 5, 6, 7]
=
array_intersect(A, B) [3, 4, 5]
array_intersect() — EXAMPLES & REAL WORLD
<?php
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];

// Common values
print_r(array_intersect($a, $b)); // [3, 4, 5]

// 1. Common tags (Blog)
$post1Tags = ["PHP", "Web", "Laravel", "MySQL"];
$post2Tags = ["PHP", "MySQL", "Database"];
$common = array_values(array_intersect($post1Tags, $post2Tags));
echo "Related tags: " . implode(", ", $common);
// Related tags: PHP, MySQL

// 2. Common user roles/permissions
$userPerms = ["read", "write", "delete"];
$pagePerms = ["read", "write"];
$allowed = array_intersect($userPerms, $pagePerms);
echo "Can: " . implode(", ", $allowed);
// Can: read, write

// 3. Mutual friends
$rahulFriends = ["Priya", "Amit", "Neha", "Raj"];
$priyaFriends = ["Rahul", "Amit", "Neha", "Sita"];
$mutual = array_values(array_intersect($rahulFriends, $priyaFriends));
echo count($mutual) . " mutual friends: " . implode(", ", $mutual);
// 2 mutual friends: Amit, Neha
?>
diff vs intersect: array_diff(A,B) = A में है, B में नहीं (difference)। array_intersect(A,B) = दोनों में है (common)। दोनों में keys first array से आती हैं।

5
array_chunk() — Array को Pages में तोड़ना
chk
()

array_chunk()

Array को fixed-size chunks में divide करता है। Pagination, batch processing, grid layouts — बहुत practical function।

PHP 4+ Returns: 2D array Pagination Must
Chunk 0
1
2
3
Chunk 1
4
5
6
Chunk 2
7
8
array array_chunk( array $array, int $length, bool $preserve_keys = false )
array_chunk() — PAGINATION & GRID
<?php
$products = ["A","B","C","D","E","F","G","H"];

// 3 per chunk
$pages = array_chunk($products, 3);
print_r($pages);
// [[A,B,C], [D,E,F], [G,H]]

// Page 1 display करना
$page = 1;
$perPage = 3;
$chunks = array_chunk($products, $perPage);
$currentPage = $chunks[$page - 1] ?? [];
echo implode(", ", $currentPage); // A, B, C

// HTML grid — 4 columns
$rows = array_chunk($products, 4);
foreach ($rows as $row) {
  echo "<div class='row'>";
  foreach ($row as $item) {
    echo "<div class='col'>$item</div>";
  }
  echo "</div>";
}

// Batch email sending
$emails = range(1, 100); // 100 emails
$batches = array_chunk($emails, 10); // 10 batches of 10
foreach ($batches as $batch) {
  echo "Sending batch of " . count($batch) . " emails\n";
}
?>

6
array_combine() — दो Arrays को जोड़ना
comb
ine

array_combine()

एक array को keys और दूसरे को values बनाकर associative array बनाता है। CSV headers + data, form fields + values।

PHP 5+ Returns: assoc array Same size required!
array array_combine( array $keys, array $values )
array_combine() — EXAMPLES
<?php
$keys = ["naam", "umar", "city"];
$values = ["Rahul", 25, "Delhi"];
$user = array_combine($keys, $values);
print_r($user);
// ["naam"=>"Rahul", "umar"=>25, "city"=>"Delhi"]

// CSV header + row combine
$headers = ["id", "name", "price", "stock"];
$row = ["101", "PHP Book", "450", "50"];
$product = array_combine($headers, $row);
echo $product["name"]; // PHP Book
echo $product["price"]; // 450

// Multiple CSV rows process करना
$csvData = [
  ["101", "PHP Book", "450"],
  ["102", "Laravel", "799"],
];
$headers = ["id", "name", "price"];
$products = array_map(
  fn($row) => array_combine($headers, $row),
  $csvData
);
print_r($products);
// [{id:101, name:PHP Book, price:450}, ...]
?>
⚠️ Same Size Required: दोनों arrays का size same होना ज़रूरी है — वरना false return होता है (PHP 8 में ValueError)। पहले check करो: count($keys) === count($values)

7
array_pad() — Array को Pad करना
pad
()

array_pad()

Array को fixed size तक pad करता है — extra positions को एक default value से fill करता है। Template slots, fixed-size data structures के लिए।

PHP 4+ Returns: padded array Positive/Negative size
array array_pad( array $array, int $length, mixed $value )
array_pad() — EXAMPLES
<?php
$arr = [1, 2, 3];

// Right pad (positive length)
print_r(array_pad($arr, 5, 0));
// [1, 2, 3, 0, 0]

// Left pad (negative length)
print_r(array_pad($arr, -5, 0));
// [0, 0, 1, 2, 3]

// Already >= size — no change
print_r(array_pad($arr, 2, 0));
// [1, 2, 3] — no padding (size >= 2)

// Real world — weekly schedule (7 days)
$tasks = ["Meeting", "Deploy"];
$week = array_pad($tasks, 7, "Free");
print_r($week);
// [Meeting, Deploy, Free, Free, Free, Free, Free]
?>

Quick Reference — Chapter 8.4
FunctionकामReturnsBest Use
count()Elements countintPagination, validation
array_sum()सब numbers जोड़int|floatCart total, stats
array_product()सब numbers गुणाint|floatFactorial, combinations
min()सबसे छोटी valuemixedCheapest price
max()सबसे बड़ी valuemixedHighest score
array_diff()A में है, B में नहींarrayMissing fields, new items
array_intersect()दोनों में commonarrayMutual friends, permissions
array_chunk()Fixed chunks में divide2D arrayPagination, grid, batches
array_combine()Keys + Values → assocassoc arrayCSV processing
array_pad()Fixed size तक fillarrayTemplates, fixed slots
🚀 अगला: Chapter 8.5 — array_column, array_rand, shuffle, json_encode, json_decode, compact, extract — Utility Array Functions।