Syntax error How to get numeric index of associative array in PHP?

How to get numeric index of associative array in PHP?



To get the numeric index of an associative array, the code is as follows−

Example

 Live Demo

<?php
   $arr = array( "a"=>"5", "b"=>"20", "c"=>"35", "d"=>"55");
   $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: a, value: 5
key: b, value: 20
key: c, value: 35
key: d, value: 55

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[3]] = "25";    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: 120
key: s, value: 25
Updated on: 2019-12-27T07:39:23+05:30

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements