Advertisement:
Read Later
In this tutorial, I will show you how to collate only key values from an array using the array_keys function in PHP.
array_keys — Return all the keys or a subset of the keys of an array(*)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
Syntax:
array_keys(array, search_value, strict)
array - An array containing keys to return.
search_value - If specified, then only keys containing these values are returned.
strict - Determines if strict comparison (===) should be used during the search.
Create an array containing employees as keys and salaries as values.
Using the array_keys() function get all employees' name and print each of them.
To obtain the name of the employee who gets the 22500 salary as integer, use the array_keys function with search_value and strict parameters.
<?php
$salary_information = array(
"John" => 18000,
"Jane" => 19500,
"David" => 20000,
"Michael" => 22000,
"Emily" => 22500
);
$employees = array_keys($salary_information);
$search_salary = array_keys($salary_information, 22500, true);
foreach($employees as $employee){
echo '<p> - '.$employee.'</p>';
}
echo '<p style="color:#002699;">Search = '.$search_salary[0].'</p>';
?>
Result:
Employees:
- John
- Jane
- David
- Michael
- Emily
Search = Emily
(*) https://www.php.net/manual/en/function.array-keys.php