Backend Development 3 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's array_keys() Function to Retrieve Array Keys

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>&lt;?php
$ace = array("one", "two", "three", "four", "Three");
print_r(array_keys($ace));
?&gt;</code>

Output:

<code>Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )</code>

b. Two parameters (search value) :

<code>&lt;?php
$ace = array("one", "two", "three", "four", "Three");
print_r(array_keys($ace, "three"));
?&gt;</code>

Output:

<code>Array ( [0] => 2 )</code>

c. Three parameters (search value with strict comparison) :

<code>&lt;?php
$ace2 = array("one", "two", "three", "four", "10", 10);
print_r(array_keys($ace2, "10"));
echo "<br>";
print_r(array_keys($ace2, "10", true));
?&gt;</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.

BackendArrayTutorialphp-functionsarray_keys
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.