How to get all the keys of an associative array in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP array_keys() function

You can use the PHP array_keys() function to get all the keys out of an associative array.

  • <?php
  • $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York");
  •  
  • // Get keys from cities array
  • print_r(array_keys($cities));
  • ?>

You can also use the PHP foreach loop to find or display all the keys.

  • <?php
  • $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York");
  •  
  • // Loop through cities array
  • foreach($cities as $key => $value){
  •     echo $key . " : " . $value . "<br>";
  • }
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.