PHP Arrays क्या है?
Complete Guide in Hindi
PHP Arrays की पूरी जानकारी हिंदी में — Indexed, Associative, Multidimensional Arrays, Array बनाना, access करना, modify करना, और 20+ Array Functions। Real examples के साथ।
📋 इस Article में क्या-क्या है (Table of Contents)
- Array क्या है?
- Indexed Array
- Associative Array
- Multidimensional Array
- Array Access & Modify
- Array के साथ Loops
- Important Array Functions
- Array Sorting
- Quick Reference Table
- FAQ और Conclusion
Array एक ऐसा variable है जो एक साथ multiple values store कर सकता है। जैसे एक class में 30 students के नाम store करने के लिए 30 अलग variables बनाने की जगह एक array बनाते हैं।
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]];// 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 के साथ
?>
// 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"...]
?>
$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";
}
?>
$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";
}
?>
$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
?>
$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
?>
End में Add
Automatically next index assign होता है।
Push — End में
एक या multiple elements end में add।
Pop — End से
Last element हटाकर return करता है।
Shift — Start से
First element हटाकर return करता है।
Unshift — Start में
Beginning में element add करता है।
Delete Specific
किसी specific index/key को हटाता है।
// 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";
}
?>
$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>
Elements count करना
Array में कितने elements हैं।
count([1,2,3]) → 3Value है या नहीं
Array में value exist करती है?
in_array("PHP", $arr) → trueValue की Key
Value का index/key return करता है।
array_search("PHP", $arr) → 1Arrays जोड़ना
दो या ज़्यादा arrays को merge करना।
array_merge($a, $b)हिस्सा निकालना
Array का portion extract करना।
array_slice($arr, 1, 3)Insert/Remove
Middle में add/remove करना।
array_splice($arr, 2, 0, ["x"])Duplicates हटाना
Unique values वाला array।
array_unique([1,2,2,3]) → [1,2,3]Keys-Values बदलना
Keys values बन जाती हैं और vice versa।
array_flip(["a"=>1]) → [1=>"a"]Filter करना
Condition के basis पर filter।
array_filter($arr, fn($x)=>$x>5)Transform करना
हर element पर function apply।
array_map('strtoupper', $arr)Single Value
Array को एक value में reduce करना।
array_reduce($arr, fn($c,$i)=>$c+$i, 0)Array → String
Array elements को string में join।
implode(", ", $arr)$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 है";
}
?>
| Function | Sorting | Keys |
|---|---|---|
| sort() | Ascending (A-Z, 0-9) | Re-index होती हैं |
| rsort() | Descending (Z-A, 9-0) | Re-index होती हैं |
| asort() | Value ascending | Keys preserve रहती हैं |
| arsort() | Value descending | Keys preserve रहती हैं |
| ksort() | Key ascending | Keys के हिसाब से sort |
| krsort() | Key descending | Keys reverse order |
| usort() | Custom function | Re-index होती हैं |
| uasort() | Custom function | Keys preserve रहती हैं |
$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
?>
| Operation | Code | Note |
|---|---|---|
| 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 start | array_unshift($arr, "x") | Re-indexes सब |
| Remove end | array_pop($arr) | Return करता है |
| Remove start | array_shift($arr) | Return करता है |
| Remove specific | unset($arr[2]) | Gap रहती है |
| Count | count($arr) | Elements की count |
| Check value | in_array("PHP", $arr) | true/false |
| Check key | array_key_exists("k", $arr) | true/false |
| Sort ascending | sort($arr) | Values sort |
| Merge | array_merge($a, $b) | Combined array |
| Unique values | array_unique($arr) | Duplicates हटाओ |
| Filter | array_filter($arr, $fn) | Condition से filter |
| Transform | array_map($fn, $arr) | हर element change |
| Reduce | array_reduce($arr, $fn, $init) | Single value |
| To string | implode(", ", $arr) | Join करना |
| From string | explode(",", $str) | Split करना |
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 करने के लिए।