Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access an associative array by integer index in PHP?
In PHP, associative arrays use string keys instead of numeric indices. To access an associative array by integer index, you need to first get the array keys using array_keys() and then use the integer index to access the corresponding key.
Basic Access Method
The most common approach is to extract all keys into an indexed array and then use integer indices to access them ?
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
$keys = array_keys($arr);
echo "Array key and value...
";
for($x = 0; $x < sizeof($arr); $x++) {
echo "key: ". $keys[$x] . ", value: ". $arr[$keys[$x]] . "
";
}
?>
Array key and value... key: p, value: 150 key: q, value: 100 key: r, value: 120 key: s, value: 110
Modifying Values by Integer Index
You can also modify associative array values using integer indices by referencing the key obtained from the keys array ?
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
$keys = array_keys($arr);
echo "Array key and value...
";
for($x = 0; $x < sizeof($arr); $x++) {
echo "key: ". $keys[$x] . ", value: ". $arr[$keys[$x]] . "
";
}
$arr[$keys[2]] = "20";
$arr[$keys[3]] = "10";
echo "\nUpdated Array key and value...
";
for($x = 0; $x < sizeof($arr); $x++) {
echo "key: ". $keys[$x] . ", value: ". $arr[$keys[$x]] . "
";
}
?>
Array key and value... key: p, value: 150 key: q, value: 100 key: r, value: 120 key: s, value: 110 Updated Array key and value... key: p, value: 150 key: q, value: 100 key: r, value: 20 key: s, value: 10
Alternative Using array_values()
For direct value access without keys, you can use array_values() to get an indexed array of values ?
<?php
$arr = array("p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
$values = array_values($arr);
echo "Accessing by integer index:
";
echo "Index 0: " . $values[0] . "
";
echo "Index 2: " . $values[2] . "
";
?>
Accessing by integer index: Index 0: 150 Index 2: 120
Conclusion
Use array_keys() to convert associative array access to integer-based indexing. This method preserves the original key-value relationships while allowing numeric index access for iteration and modification.
