PHP print keys from an object?


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

To display only the keys from an object, use array_keys() in PHP.

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?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>";
?>
</body>
</html>

Output

All Keys are as follows=
firstName
lastName
countryName

Updated on: 12-Oct-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements