Backend Development 5 min read

Using PHP array_keys() Function: Syntax, Parameters, and Practical Examples

This article explains the PHP array_keys() function, detailing its syntax and optional parameters, and provides three clear code examples that demonstrate how to retrieve keys from indexed, associative, and multidimensional arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_keys() Function: Syntax, Parameters, and Practical Examples

In PHP there are many powerful array handling functions, and array_keys() is a very useful function that returns a new array containing all the key names of a given array.

The syntax of array_keys() is:

array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] ) : array

Parameters:

$array : The array from which to retrieve the keys.

$search_value (optional): If provided, only keys whose corresponding values are equal to $search_value are returned.

$strict (optional): When set to true , a strict comparison (both type and value) is used.

Below are several examples of using array_keys() :

Example 1 – Indexed array:

<?php
// Create an array
$fruits = array("apple", "banana", "orange", "apple", "grape");
// Get all keys
$keys = array_keys($fruits);
// Print result
print_r($keys);
?>

Output:

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

Example 2 – Associative array:

<?php
// Create an associative array
$student_scores = array("Mike" => 85, "John" => 92, "Sarah" => 78);
// Get all keys
$keys = array_keys($student_scores);
// Print result
print_r($keys);
?>

Output:

Array
(
    [0] => Mike
    [1] => John
    [2] => Sarah
)

Example 3 – Multidimensional array:

<?php
// Create a multidimensional array
$students = array(
    array("name" => "Mike", "age" => 20),
    array("name" => "John", "age" => 22),
    array("name" => "Sarah", "age" => 19)
);
// Get keys of the first sub‑array
$names = array_keys($students[0]);
// Print result
print_r($names);
?>

Output:

Array
(
    [0] => name
    [1] => age
)

These examples show that array_keys() can conveniently retrieve all keys from indexed arrays, associative arrays, and even multidimensional arrays, making it a versatile tool in PHP development.

In summary, the array_keys() function is a concise and flexible way to obtain the keys of any array in PHP, and its simplicity and power make it highly practical for real‑world coding tasks.

backendarraysphp-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.