Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Access Associative Array by Integer Index in PHP



To access an associative array by integer index in PHP, the code is as follows−

Example

 Live Demo

<?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]] . "
";    } ?>

Output

This will produce the following output−

Array key and value...
key: p, value: 150
key: q, value: 100
key: r, value: 120
key: s, value: 110

Example

Let us now see another example−

 Live Demo

<?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 "
Updated Array key and value...
";    for($x = 0; $x < sizeof($arr); $x++ ) {       echo "key: ". $keys[$x] . ", value: ". $arr[$keys[$x]] . "
";    } ?>

Output

This will produce the following output−

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
Updated on: 2019-12-26T10:37:25+05:30

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements