Backend Development 5 min read

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

This article explains PHP's array_keys() function, detailing its syntax, optional parameters, and demonstrating its use with indexed, associative, and multidimensional arrays through clear code examples and output illustrations.

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

PHP provides a powerful set of array handling functions, and array_keys() is one of the most useful for retrieving all key names from a given array.

The function signature is:

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

Parameters:

$array : The input array whose keys you want to retrieve.

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

$strict (optional): When set to true , the comparison uses strict type checking.

Example 1 – Indexed array:

<?php
// Create an indexed array
$fruits = array("apple", "banana", "orange", "apple", "grape");
// Retrieve all keys
$keys = array_keys($fruits);
// Print the 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);
// Retrieve all keys
$keys = array_keys($student_scores);
// Print the 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)
);
// Retrieve keys from the first sub‑array
$names = array_keys($students[0]);
// Print the result
print_r($names);
?>

Output:

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

These examples demonstrate that array_keys() works seamlessly with indexed, associative, and even multidimensional arrays, making it a versatile tool for extracting key information in PHP development.

Summary

In PHP, the array_keys() function returns a new array containing all the keys from the input array, regardless of whether the array is indexed, associative, or multidimensional. Its concise syntax and flexible parameters make it extremely useful in everyday backend programming.

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