PHP print keys from an object?

In PHP, you can extract keys from an object using the array_keys() function. This is useful when you need to access property names dynamically or iterate through object properties.

Let's say the following is our object −

$employeeDetails = (object) [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'countryName' => 'US'
];

We want the following output i.e. only the keys −

firstName
lastName
countryName

Using array_keys() Method

To display only the keys from an object, use array_keys() after casting the object to an array ?

<?php
$employeeDetails = (object) [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'countryName' => 'US'
];

$allKeysOfEmployee = array_keys((array)$employeeDetails);
echo "All Keys are as follows:<br>";
foreach($allKeysOfEmployee as $tempKey) {
    echo $tempKey . "<br>";
}
?>
All Keys are as follows:
firstName
lastName
countryName

Alternative Method: Using get_object_vars()

Another approach is using get_object_vars() which directly returns an associative array of object properties ?

<?php
$employeeDetails = (object) [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'countryName' => 'US'
];

$objectKeys = array_keys(get_object_vars($employeeDetails));
foreach($objectKeys as $key) {
    echo $key . "<br>";
}
?>
firstName
lastName
countryName

Conclusion

Use array_keys((array)$object) or array_keys(get_object_vars($object)) to extract keys from PHP objects. Both methods work effectively for accessing object property names programmatically.

Updated on: 2026-03-15T09:30:34+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements