Program:Program for traversing an associative array and print keys.
Php
// We iterate over the associative array and get
// the key of the associative array
// Associative array
$person_weight
=
array
(
"Rajnish"
= > 58,
"Sanjeev"
= > 55,
"Ravi"
= > 60,
"Yash"
= > 60,
"Suraj"
= > 48
);
// Use a for-each loop and render
// associative array key
foreach
(
$person_weight
as
$key
= >
$value
) {
echo
" Key: "
.
$key
.
""
;
}
?>
Exit:Key: Rajnish Key: Sanjeev Key: Ravi Key: Yash Key: SurajMethod 2: Using the function array_keys(): array_keys() - is a built-in PHP function that is used to return either all keys in an array or a subset of keys.Syntax:
array_keys ($input_array, $search_value , $strict)Program:The program below illustrates the use of the array_keys() function to access the keys of an associative array.
php
// Use array_keys() to display
// associative array key
// Associative array
$assoc_array
=
array
(
" Geeks "
= > 30,
"for"
= > 20,
"engineer"
= > 10
);
// Using the array_keys() function
$key
=
array_keys
(
$assoc_array
);
// Calculate array size
$size
= sizeof (
$key
);
// Using a loop to access keys
for
(
$i
= 0;
$i
<
$size
;
$i
++) {
echo
"key: ${key [$i]}"
;
}
?>
Exit:key: Geeks key: for key: engineer