PHP Arrays Introduction
In this page:
$array = [value1, value2, value3];
$array = array(value1, value2); // older syntax
print_r($array);
count($array);
Array क्या है
PHP में एक array एक single ordered collection है जो एक variable name के तहत कई values रख सकता है, आपको related data group करने देते हुए — जैसे usernames की एक list — हर item के लिए एक अलग variable बनाने के बजाय।
उदाहरण: What is an Array
<?php
// Declare `$usernames` as an array: `["alice", "bob", "carol"]`
$usernames = ["alice", "bob", "carol"];
// Print a human-readable dump of `$usernames`
print_r($usernames);
?>
Login to try C/C++/Java/PHP code in the editor
Arrays Print करना
PHP arrays असामान्य रूप से flexible हैं: वही array() या [] structure एक numerically indexed list, एक associative key-value map, या दोनों का mix की तरह behave कर सकता है, उन languages के उलट जो दोनों के बीच एक strict choice force करती हैं।
उदाहरण: Printing Arrays
<?php
// Declare `$mixed` as an array: `["name" => "Alice", 0 => "first", 1 => "second"]`
$mixed = ["name" => "Alice", 0 => "first", 1 => "second"];
// Print a human-readable dump of `$mixed`
print_r($mixed);
?>
Login to try C/C++/Java/PHP code in the editor
Array Size Check करना
आप short [] syntax (या पुराने array() function) से एक array बनाते हैं और अधिक complex structures represent करने के लिए arrays के अंदर arrays nest कर सकते हैं, जैसे orders की एक list जहाँ हर order खुद details का एक array है।
उदाहरण: Checking Array Size
<?php
$orders = [
["id" => 1, "item" => "Book"],
["id" => 2, "item" => "Pen"],
];
// Print a human-readable dump of `$orders`
print_r($orders);
?>
Login to try C/C++/Java/PHP code in the editor
Array Types Check करना
count() आपको बताता है कि किसी array में कितने elements हैं, जो इस पर loop चलाने या यह validate करने से पहले ज़रूरी है कि किसी form ने expected संख्या में items submit किए।
उदाहरण: Checking Array Types
<?php
// Declare `$items` as an array: `["a", "b", "c"]`
$items = ["a", "b", "c"];
// Print `count($items)` to the output
echo count($items);
?>
Login to try C/C++/Java/PHP code in the editor
Foreach से Iterate करना
PHP में arrays default रूप से value से pass होते हैं, यानी एक function जो एक array receive करता है और उसे modify करता है वह एक copy पर काम कर रहा है जब तक आप इसे explicitly एक & के साथ reference से pass न करें — एक detail जो कई beginners को confuse करती है।
उदाहरण: Iterating with Foreach
<?php
function addItem($arr) {
$arr[] = "new";
}
$list = ["a", "b"];
addItem($list);
print_r($list); // unchanged -- array was passed by value
?>
Login to try C/C++/Java/PHP code in the editor
echo $arrसे किसी array को print करना, जो शब्दArrayऔर एक notice output करता है;print_rयाvar_dumpइस्तेमाल करें।- एक ऐसी key पढ़ना जो exist नहीं करती, जो एक undefined array key के बारे में एक warning raise करता है।
- यह मान लेना कि
count($arr)last index देता है, जबकि last indexcount($arr) - 1है।
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: