In PHP, the array_keys() function is a very useful tool for array manipulation. It returns all the keys from a given array. Whether the array is indexed, associative, or multidimensional, array_keys() helps you efficiently retrieve the keys. This article will explain how to use the array_keys() function with multiple examples.
The syntax of the array_keys() function is as follows:
array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] ) : array
First, let's create an indexed array containing duplicate values and use array_keys() to get all the keys.
<?php
// Create an array
$fruits = array("apple", "banana", "orange", "apple", "grape");
// Get all the keys from the array
$keys = array_keys($fruits);
// Print the result
print_r($keys);
?>
Output:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
In this example, we created an array with duplicate elements. The array_keys() function returns all the keys from the array, and we print the result using the print_r() function.
Next, let's create an associative array containing student names and scores, and use array_keys() to retrieve all the keys.
<?php
// Create an associative array
$student_scores = array("Mike" => 85, "John" => 92, "Sarah" => 78);
// Get all the keys from the array
$keys = array_keys($student_scores);
// Print the result
print_r($keys);
?>
Output:
Array
(
[0] => Mike
[1] => John
[2] => Sarah
)
This example demonstrates how to get all the keys (student names) from an associative array.
In this example, we create a multidimensional array containing student information and retrieve the keys for the first student's data.
<?php
// Create a multidimensional array
$students = array(
array("name" => "Mike", "age" => 20),
array("name" => "John", "age" => 22),
array("name" => "Sarah", "age" => 19)
);
// Get all keys from the first student's data
$names = array_keys($students[0]);
// Print the result
print_r($names);
?>
Output:
Array
(
[0] => name
[1] => age
)
This example shows how to use array_keys() to get the keys for the first student's information from a multidimensional array.
The array_keys() function is an essential tool for working with arrays in PHP. Whether the array is indexed, associative, or multidimensional, array_keys() makes it easy to retrieve all the keys from an array. After going through the examples in this article, you should have a clear understanding of how to use this function effectively in your PHP projects. We hope this guide helps you in your development work.