PHP Basics · Beginner Level · Chapter 8

PHP Arrays क्या है?
Complete Guide in Hindi

PHP Arrays की पूरी जानकारी हिंदी में — Indexed, Associative, Multidimensional Arrays, Array बनाना, access करना, modify करना, और 20+ Array Functions। Real examples के साथ।

📦 3 Types of Arrays 🔑 Keys & Values 🔁 Loops with Arrays ⏱️ 12 min read 📝 2000+ words
3Types of Arrays
0Index शुरू होता है
75+PHP Array Functions
[ ]Modern array syntax

📋 इस Article में क्या-क्या है (Table of Contents)

  1. Array क्या है?
  2. Indexed Array
  3. Associative Array
  4. Multidimensional Array
  5. Array Access & Modify
  6. Array के साथ Loops
  7. Important Array Functions
  8. Array Sorting
  9. Quick Reference Table
  10. FAQ और Conclusion
1
Array क्या है?

Array एक ऐसा variable है जो एक साथ multiple values store कर सकता है। जैसे एक class में 30 students के नाम store करने के लिए 30 अलग variables बनाने की जगह एक array बनाते हैं।

Real life example — shopping cart में multiple items, students की list, product categories — यह सब arrays में store होता है। PHP में array एक ordered map है — keys और values का collection।
Array = एक variable, multiple values। जैसे एक डिब्बे में बहुत सारी चीज़ें।
📋

Indexed Array

Numeric keys (0, 1, 2...) automatically assign होते हैं।

$arr = ["Apple", "Mango"];
🗝️

Associative Array

Custom string keys define करते हैं। Key-value pairs।

$user = ["naam" => "Rahul"];
🗂️

Multidimensional Array

Array के अंदर array। Database rows जैसा structure।

$matrix = [[1,2], [3,4]];

2
Indexed Array — Numeric Keys
Indexed Array में values automatically 0 से numbered होती हैं। पहला element index 0, दूसरा 1, और इसी तरह।
[0]
"Apple"
[1]
"Mango"
[2]
"Banana"
[3]
"Orange"
INDEXED ARRAY — बनाना और Access करना
<?php
// Method 1 — [] syntax (Modern, Recommended)
$fruits = ["Apple", "Mango", "Banana", "Orange"];

// Method 2 — array() function (Old style)
$colors = array("Red", "Green", "Blue");

// Access — index number से
echo $fruits[0]; // Apple
echo $fruits[1]; // Mango
echo $fruits[3]; // Orange

// Last element — count()-1
$last = $fruits[count($fruits) - 1];
echo $last; // Orange

// Add element
$fruits[] = "Grapes"; // index 4 पर add होगा
$fruits[10] = "Kiwi"; // specific index पर

// Array info
echo count($fruits); // 6 (total elements)
print_r($fruits); // Full array देखो
var_dump($fruits); // Types के साथ
?>
💡 Tip: $arr[]= "value" automatically next available index पर add करता है। यह सबसे common way है element add करने का।

3
Associative Array — Custom Keys
Associative Array में आप खुद keys define करते हैं — string keys। हर key एक meaningful name है। Database row की तरह होता है — column name = key, value = data।
"naam"
=>
"Rahul Kumar"
"umar"
=>
25
"city"
=>
"Delhi"
"job"
=>
"Developer"
ASSOCIATIVE ARRAY — Examples
<?php
// Associative array बनाना
$user = [
  "naam" => "Rahul Kumar",
  "umar" => 25,
  "city" => "Delhi",
  "email" => "rahul@gmail.com"
];

// Key से access
echo $user["naam"]; // Rahul Kumar
echo $user["city"]; // Delhi

// Value update करना
$user["city"] = "Mumbai";

// New key add करना
$user["phone"] = "9876543210";

// Key exist check
if (array_key_exists("email", $user)) {
  echo "Email: " . $user["email"];
}

// Keys और Values अलग निकालना
$keys = array_keys($user); // ["naam","umar","city"...]
$values = array_values($user); // ["Rahul",25,"Delhi"...]
?>
ASSOCIATIVE ARRAY — Real World: Product
<?php
$product = [
  "id" => 101,
  "name" => "PHP Book",
  "price" => 450.00,
  "stock" => 25,
  "inStock" => true,
  "category" => "Books"
];

echo "Product: " . $product["name"];
echo "Price: ₹" . $product["price"];
echo "Stock: " . $product["stock"];

if ($product["inStock"]) {
  echo "✅ Available";
} else {
  echo "❌ Out of Stock";
}
?>

4
Multidimensional Array — Array के अंदर Array
Multidimensional Array में हर element खुद एक array होता है। Database table की तरह — rows और columns। Students list, products catalog, user orders — इन सबके लिए।
2D ARRAY — Students List
<?php
$students = [
  ["naam" => "Rahul", "marks" => 95, "grade" => "A"],
  ["naam" => "Priya", "marks" => 88, "grade" => "B"],
  ["naam" => "Amit", "marks" => 72, "grade" => "C"],
  ["naam" => "Neha", "marks" => 91, "grade" => "A"],
];

// Access — [row][key]
echo $students[0]["naam"]; // Rahul
echo $students[0]["marks"]; // 95
echo $students[2]["naam"]; // Amit

// सभी students display करना
foreach ($students as $student) {
  echo $student["naam"] . ": " . $student["marks"] . " (" . $student["grade"] . ")\n";
}
?>
3D ARRAY — School → Class → Students
<?php
$school = [
  "Class 10A" => [
    ["naam" => "Rahul", "roll" => 1],
    ["naam" => "Priya", "roll" => 2],
  ],
  "Class 10B" => [
    ["naam" => "Amit", "roll" => 1],
    ["naam" => "Neha", "roll" => 2],
  ],
];

// 3 levels deep access
echo $school["Class 10A"][0]["naam"]; // Rahul
echo $school["Class 10B"][1]["naam"]; // Neha
?>

5
Array Access, Modify & Delete
CRUD OPERATIONS on Arrays
<?php
$cart = ["Book", "Pen", "Notebook"];

// READ — access
echo $cart[0]; // Book
echo count($cart); // 3

// CREATE — add elements
$cart[] = "Pencil"; // End में add
array_unshift($cart, "Eraser"); // Start में add

// UPDATE — modify
$cart[0] = "Ruler"; // Value change

// DELETE — remove elements
unset($cart[1]); // Specific index हटाओ
array_pop($cart); // Last element हटाओ
array_shift($cart); // First element हटाओ

// Re-index करना (unset के बाद gaps आते हैं)
$cart = array_values($cart); // 0,1,2... re-index
?>
$arr[]
End में Add

Automatically next index assign होता है।

array_push()
Push — End में

एक या multiple elements end में add।

array_pop()
Pop — End से

Last element हटाकर return करता है।

array_shift()
Shift — Start से

First element हटाकर return करता है।

array_unshift()
Unshift — Start में

Beginning में element add करता है।

unset()
Delete Specific

किसी specific index/key को हटाता है।


6
Array के साथ Loops
Arrays को process करने के लिए foreach loop सबसे best है — specifically arrays के लिए design हुई है। for loop भी use होता है indexed arrays के साथ।
FOREACH — सभी Array Types के साथ
<?php
// 1. Indexed Array — foreach
$fruits = ["Apple", "Mango", "Banana"];
foreach ($fruits as $fruit) {
  echo $fruit . "\n"; // Apple, Mango, Banana
}

// 2. Index के साथ
foreach ($fruits as $index => $fruit) {
  echo "$index: $fruit\n"; // 0: Apple, 1: Mango...
}

// 3. Associative Array — key => value
$user = ["naam" => "Rahul", "city" => "Delhi"];
foreach ($user as $key => $value) {
  echo "$key: $value\n"; // naam: Rahul, city: Delhi
}

// 4. Multidimensional Array
$students = [
  ["naam" => "Rahul", "marks" => 95],
  ["naam" => "Priya", "marks" => 88],
];
foreach ($students as $s) {
  echo "{$s['naam']}: {$s['marks']}\n";
}
?>
HTML TABLE बनाना — Array से
<?php
$products = [
  ["name" => "PHP Book", "price" => 450],
  ["name" => "Laravel Guide", "price" => 799],
  ["name" => "MySQL Notes", "price" => 299],
];
?>
<table><tr><th>Product</th><th>Price</th></tr>
<?php foreach ($products as $p): ?>
<tr>
  <td><?= htmlspecialchars($p['name']) ?></td>
  <td><?= $p['price'] ?></td>
</tr>
<?php endforeach; ?>
</table>

7
Important Array Functions
count()
Elements count करना

Array में कितने elements हैं।

count([1,2,3]) → 3
in_array()
Value है या नहीं

Array में value exist करती है?

in_array("PHP", $arr) → true
array_search()
Value की Key

Value का index/key return करता है।

array_search("PHP", $arr) → 1
array_merge()
Arrays जोड़ना

दो या ज़्यादा arrays को merge करना।

array_merge($a, $b)
array_slice()
हिस्सा निकालना

Array का portion extract करना।

array_slice($arr, 1, 3)
array_splice()
Insert/Remove

Middle में add/remove करना।

array_splice($arr, 2, 0, ["x"])
array_unique()
Duplicates हटाना

Unique values वाला array।

array_unique([1,2,2,3]) → [1,2,3]
array_flip()
Keys-Values बदलना

Keys values बन जाती हैं और vice versa।

array_flip(["a"=>1]) → [1=>"a"]
array_filter()
Filter करना

Condition के basis पर filter।

array_filter($arr, fn($x)=>$x>5)
array_map()
Transform करना

हर element पर function apply।

array_map('strtoupper', $arr)
array_reduce()
Single Value

Array को एक value में reduce करना।

array_reduce($arr, fn($c,$i)=>$c+$i, 0)
implode()
Array → String

Array elements को string में join।

implode(", ", $arr)
ARRAY FUNCTIONS — Real Examples
<?php
$marks = [85, 92, 78, 95, 88, 72, 92];

// count — total students
echo count($marks); // 7

// array_unique — duplicate marks हटाओ
$unique = array_unique($marks); // 85,92,78,95,88,72

// array_filter — 90+ marks वाले
$toppers = array_filter($marks, fn($m) => $m >= 90);
echo count($toppers); // 3 (92, 95, 92)

// array_map — सबको 5 bonus marks दो
$withBonus = array_map(fn($m) => $m + 5, $marks);

// array_reduce — total marks
$total = array_reduce($marks, fn($carry, $item) => $carry + $item, 0);
$avg = $total / count($marks);
echo "Average: " . round($avg, 2); // Average: 86

// in_array — 95 marks है?
if (in_array(95, $marks)) {
  echo "✅ 95 marks वाला student है";
}
?>

8
Array Sorting Functions
PHP में arrays को sort करने के लिए कई functions हैं — ascending, descending, custom order — सब possible।
FunctionSortingKeys
sort()Ascending (A-Z, 0-9)Re-index होती हैं
rsort()Descending (Z-A, 9-0)Re-index होती हैं
asort()Value ascendingKeys preserve रहती हैं
arsort()Value descendingKeys preserve रहती हैं
ksort()Key ascendingKeys के हिसाब से sort
krsort()Key descendingKeys reverse order
usort()Custom functionRe-index होती हैं
uasort()Custom functionKeys preserve रहती हैं
SORTING — Examples
<?php
$nums = [5, 2, 8, 1, 9, 3];

// sort — ascending
sort($nums);
print_r($nums); // [1, 2, 3, 5, 8, 9]

// rsort — descending
rsort($nums);
print_r($nums); // [9, 8, 5, 3, 2, 1]

// Associative sort — keys preserve
$scores = ["Rahul" => 95, "Priya" => 88, "Amit" => 92];
arsort($scores); // Rahul=>95, Amit=>92, Priya=>88

// usort — custom sorting (price से)
$products = [
  ["name" => "Book", "price" => 450],
  ["name" => "Pen", "price" => 50],
  ["name" => "Bag", "price" => 800],
];
usort($products, fn($a, $b) => $a["price"] <=> $b["price"]);
// Pen(50), Book(450), Bag(800) — price ascending
?>

9
Quick Reference — Arrays एक नज़र में
OperationCodeNote
Create indexed$arr = [1, 2, 3];0 से start
Create associative$arr = ["key" => "val"];Custom keys
Access$arr[0] या $arr["key"]Index या key से
Add end$arr[] = "new";Next index auto
Add startarray_unshift($arr, "x")Re-indexes सब
Remove endarray_pop($arr)Return करता है
Remove startarray_shift($arr)Return करता है
Remove specificunset($arr[2])Gap रहती है
Countcount($arr)Elements की count
Check valuein_array("PHP", $arr)true/false
Check keyarray_key_exists("k", $arr)true/false
Sort ascendingsort($arr)Values sort
Mergearray_merge($a, $b)Combined array
Unique valuesarray_unique($arr)Duplicates हटाओ
Filterarray_filter($arr, $fn)Condition से filter
Transformarray_map($fn, $arr)हर element change
Reducearray_reduce($arr, $fn, $init)Single value
To stringimplode(", ", $arr)Join करना
From stringexplode(",", $str)Split करना

10
अक्सर पूछे जाने वाले सवाल (FAQ)
Q: Array और Variable में क्या फर्क है?
Variable एक single value store करता है — $naam = "Rahul"। Array multiple values एक name से store करता है — $students = ["Rahul", "Priya", "Amit"]। 30 students के लिए 30 variables की जगह एक array बनाओ।
Q: array_push() और $arr[] में क्या फर्क है?
दोनों end में element add करते हैं। $arr[] = "value" faster है और more commonly used। array_push() एक साथ multiple elements add कर सकता है: array_push($arr, "a", "b", "c")। Performance के लिए $arr[] prefer करो।
Q: unset() के बाद array को re-index कैसे करें?
unset() element हटाता है लेकिन gap छोड़ देता है। जैसे [0,1,2] में index 1 unset करने पर [0=>a, 2=>c] रहेगा। Re-index के लिए: $arr = array_values($arr); — यह 0 से फिर number करता है।
Q: foreach में array modify कर सकते हैं?
Normally foreach copy पर iterate करता है — changes original array में नहीं जाते। Reference से iterate करने के लिए foreach ($arr as &$item) use करो। Loop के बाद unset($item) ज़रूर करो — dangling reference से बचाता है।
Q: Array को JSON में कैसे convert करें?
json_encode($array) — PHP array को JSON string में convert करता है। json_decode($json, true) — JSON string को PHP array में convert करता है। API responses, AJAX calls, और data storage के लिए बहुत useful।
Q: array_map() और foreach में क्या फर्क है?
foreach imperative style है — आप खुद loop handle करते हो। array_map() functional style है — cleaner code, new array return करता है। $doubled = array_map(fn($x) => $x*2, $arr); — यह foreach से shorter और readable है। Modern PHP में array_map, array_filter prefer होते हैं।

निष्कर्ष (Conclusion)

PHP Arrays सबसे powerful data structure है। Real PHP applications में हर जगह arrays होते हैं — database results, form data, API responses, shopping carts। Arrays master करना PHP mastery का core है।

3 Types — Indexed (numeric keys), Associative (string keys), Multidimensional (nested)।

foreach सबसे best loop है arrays के लिए — key => value दोनों access होते हैं।

array_map, array_filter, array_reduce — modern functional style। Clean code।

usort + spaceship operator — custom sorting का best way।

json_encode/decode — Arrays को API और AJAX में use करने के लिए।

array_values() — unset के बाद gaps fill करने के लिए।

🚀 अगला कदम: Arrays clear हो गए? अगला series होगा Chapter 8.1, 8.2, 8.3 — Array Functions की deep dive। फिर Chapter 9: PHP Loops — for, while, foreach, do-while सब detail में।