Associative array के keys को numeric index के साथ access करने के तरीके।
विधि 1: array_keys() + Index Access
<?php
$arr = ['p' => 150, 'q' => 100, 'r' => 120, 's' => 110];
$keys = array_keys($arr);
// $keys = ['p', 'q', 'r', 's']
// Numeric index द्वारा access
echo "Index 0: key={$keys[0]}, value={$arr[$keys[0]]}\n"; // p, 150
echo "Index 2: key={$keys[2]}, value={$arr[$keys[2]]}\n"; // r, 120
// Loop with numeric index
for ($i = 0; $i < count($arr); $i++) {
$key = $keys[$i];
echo "[$i] $key => {$arr[$key]}\n";
}
विधि 2: array_values() - केवल Values चाहिए तो
<?php $arr = ['p' => 150, 'q' => 100, 'r' => 120, 's' => 110]; $values = array_values($arr); // [150, 100, 120, 110] - keys 0,1,2,3 echo $values[2]; // 120 (third element)
विधि 3: Iterator (Memory Efficient)
<?php
$arr = ['p' => 150, 'q' => 100, 'r' => 120, 's' => 110];
$iterator = new ArrayIterator($arr);
// Seek to specific index
$iterator->seek(2);
echo "Index 2: {$iterator->key()} => {$iterator->current()}\n"; // r => 120
// Iterate with index
foreach ($iterator as $index => $value) {
echo "[$index] {$iterator->key()} => $value\n";
}
विधि 4: Numeric Keys में Convert (Permanent)
<?php $arr = ['p' => 150, 'q' => 100, 'r' => 120, 's' => 110]; // Re-index to 0, 1, 2, 3 $arr = array_values($arr); // या custom start $arr = array_combine(range(10, 10 + count($arr) - 1), array_values($arr)); // [10 => 150, 11 => 100, 12 => 120, 13 => 110]
व्यावहारिक उदाहरण: Pagination
<?php
function getPaginatedAssoc(array $data, int $page, int $perPage): array {
$keys = array_keys($data);
$total = count($keys);
$offset = ($page - 1) * $perPage;
if ($offset >= $total) return [];
$pageKeys = array_slice($keys, $offset, $perPage);
$result = [];
foreach ($pageKeys as $key) {
$result[$key] = $data[$key];
}
return $result;
}
$data = array_combine(range('a', 'z'), range(1, 26));
print_r(getPaginatedAssoc($data, 2, 5)); // Page 2, 5 per page
Important: Order Guarantee
PHP 7+ में arrays insertion order maintain करते हैं।
array_keys()औरarray_values()उसी order में return करते हैं। PHP < 7 में भी associative arrays ordered थे।
Performance Note
<?php
$large = array_combine(range('a', 'z'), range(1, 26)); // Small for demo
// array_keys() creates new array - O(n) memory
$keys = array_keys($large);
// Direct access by known key - O(1)
$value = $large['m'];
// यदि बार-बार numeric index से access करना है, array_values() एक बार करें:
$values = array_values($large); // O(n) once
// फिर $values[$index] - O(1) हर बार