How to Use PHP's array_keys() Function to Retrieve Array Keys
This article explains PHP's array_keys() function, detailing its syntax, parameters, return values, and demonstrating three practical examples that show how to retrieve array keys with optional search values and strict comparison.
Arrays are a common data type in PHP, and developers often need to obtain their keys; PHP provides the array_keys() function for this purpose.
Syntax :
<code>array_keys ( array $array , mixed $search_value = null , bool $strict = false )</code>Parameters :
$array : The array whose keys you want to retrieve.
$search_value (optional): If provided, only keys of elements matching this value are returned; default is null .
$strict (optional): When set to true , the function uses strict comparison ( === ) for the search value; default is false .
Return value : An indexed array containing the keys that match the criteria.
Practical examples :
a. Only one parameter :
<code><?php
$ace = array("one", "two", "three", "four", "Three");
print_r(array_keys($ace));
?></code>Output:
<code>Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )</code>b. Two parameters (search value) :
<code><?php
$ace = array("one", "two", "three", "four", "Three");
print_r(array_keys($ace, "three"));
?></code>Output:
<code>Array ( [0] => 2 )</code>c. Three parameters (search value with strict comparison) :
<code><?php
$ace2 = array("one", "two", "three", "four", "10", 10);
print_r(array_keys($ace2, "10"));
echo "<br>";
print_r(array_keys($ace2, "10", true));
?></code>Output:
<code>Array ( [0] => 4 [1] => 5 )
Array ( [0] => 4 )</code>When the third parameter $strict is set to true , the function performs a strict comparison, distinguishing between the string "10" and the integer 10 .
For the full article, click the "Read Original" link in the source.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.