PHP में array_fill_keys() फ़ंक्शन निर्दिष्ट कुंजियों (keys) वाली सरणी बनाता है और सभी को समान मान (value) से भर देता है।
सिंटैक्स (Syntax)
array_fill_keys(array $keys, mixed $value): array
पैरामीटर्स (Parameters)
$keys − कुंजियों की सरणी (ये नई सरणी की कुंजियाँ बनेंगी)।
$value − सभी कुंजियों के लिए भरा जाने वाला मान।
रिटर्न वैल्यू (Return Value)
निर्दिष्ट कुंजियों और दिए गए मान से भरी सरणी लौटाता है।
उदाहरण (Examples)
उदाहरण 1: मूल उपयोग
<?php
$keys = array('p', 'q', 'r');
$result = array_fill_keys($keys, 'demo');
print_r($result);
?>
आउटपुट
Array
(
[p] => demo
[q] => demo
[r] => demo
)
उदाहरण 2: मिश्रित प्रकार की कुंजियाँ
<?php
$keys = array('a', 'b', 'c', 1, 2, 3, 'steve', 'tom', 4, 5);
$result = array_fill_keys($keys, 'demo');
print_r($result);
?>
आउटपुट
Array
(
[a] => demo
[b] => demo
[c] => demo
[1] => demo
[2] => demo
[3] => demo
[steve] => demo
[tom] => demo
[4] => demo
[5] => demo
)
उदाहरण 3: व्यावहारिक उपयोग - डिफ़ॉल्ट मानों के साथ सरणी प्रारंभ करना
<?php $fields = ["name", "email", "phone", "address"]; $defaults = array_fill_keys($fields, ""); // या डेटाबेस से डिफ़ॉल्ट: $defaults = array_fill_keys($fields, null); print_r($defaults); ?>
उदाहरण 4: array_fill() से तुलना
<?php // array_fill_keys: कुंजियाँ आप देते हैं array_fill_keys(['a', 'b'], 'x'); // ['a'=>'x', 'b'=>'x'] // array_fill: संख्यात्मक कुंजियाँ स्वतः बनती हैं array_fill(0, 2, 'x'); // [0=>'x', 1=>'x'] array_fill(5, 3, 'x'); // [5=>'x', 6=>'x', 7=>'x'] ?>
नोट
- यदि $keys में डुप्लिकेट हैं, तो अंतिम मान जीतता है (कुंजियाँ अद्वितीय होनी चाहिए)।
- $value किसी भी प्रकार का हो सकता है (सरणी, ऑब्जेक्ट, null, आदि)।
- सभी कुंजियों को समान मान चाहिए तो उपयोगी; अलग-अलग मानों के लिए
array_combine()उपयोग करें।