Skip to content
Related Articles

Related Articles

How to access an associative array by integer index in PHP?
  • Last Updated : 11 Feb, 2019

There are two types of arrays in PHP, indexed and associative arrays. In case of indexed array strict numeric indexing is followed but in case of associative array there are keys corresponding to each element.
The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP.

Although the array_keys() function can be used to get an indexed array of keys for an associative array. As the resulting array is indexed the elements of the resulting array can be accessed by integer index. Using this resulting array, the keys of the original array can be accessed by integer index and then the keys can be used to access the elements of the original array. Thus by using the integer index the elements of the original array can be accessed with the help of an additional indexed array of keys.

array_keys() function: The array_keys() function takes an array as input and returns an indexed array which consists only the keys of the original array, indexed where indexing is started from zero.

Syntax:

array array_keys( $arr )

Parameters: The array_keys() function takes an array as input and use only the keys of the array to make the indexed resulting array.



Note: The array_keys() function does not change the order of the keys of the original array. If an indexed array is passed then the resulting array will have integers as value.

Program: PHP program to access an associative array using integer index.




<?php
// PHP program to accessing an associative
// array by integer index
  
// Sample associative array
$arr = array( 'one' => 'geeks',
              'two' => 'for'
              'three' => 'geeks'
        );
      
// Getting the keys of $arr
// using array_keys() function
$keys = array_keys( $arr );
      
echo "The keys array: ";
  
print_r($keys);
      
// Getting the size of the sample array
$size = sizeof($arr);
      
//Accessing elements of $arr using
//integer index using $x
echo "The elements of the sample array: " . "\n";
  
for($x = 0; $x < $size; $x++ ) {
    echo "key: ". $keys[$x] . ", value: " 
            . $arr[$keys[$x]] . "\n";
}
      
?>


Output:

The keys array: Array
(
    [0] => one
    [1] => two
    [2] => three
)
The elements of the sample array: 
key: one, value: geeks
key: two, value: for
key: three, value: geeks
My Personal Notes arrow_drop_up
Recommended Articles
Page :