You are here: Home / Topics / How to get all the keys of an associative array in PHP

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

Filed under: PHP on 2023-07-02 21:21:53

You can use the PHP array_keys() function to extract all the keys from an associative array.
 

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

<?php
 $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML");
 print_r(array_keys($languages));
?>
 

Output:

Array ( 
[0] => p 
[1] => j 
[2] => a 
[3] => h 
)

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

<?php
 $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML");
 
 foreach($languages as $key => $value){
   echo $key . " : " . $value . "<br>";
 }
?>
 

Output:

p : PHP
j : Java
a : Ada
h : HTML

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.