PHP print keys from an object?

PHPServer Side ProgrammingProgramming

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
raja
Published on 12-Oct-2020 13:32:37
Advertisements