PHP Array array_keys() Function (With Examples)

In this tutorial, we will learn about the PHP array_keys() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_keys() function

The array_keys() function is used to get the keys of an array, it accepts an array as an argument and returns a new array containing keys.

Syntax

The syntax of the array_keys() function:

array_keys(input_array, [value], [strict]);

Parameters

The parameters of the array_keys() function:

  • input_array is an array (i.e. input array).
  • value is an optional parameter, it is used to define a value if the value is defined, then the only keys having that value are returned.
  • strict is also an optional parameter, it is default set to false if we set it true the type of values will be checked.

Return Value

The return type of this method is array, it returns an array of all the keys in array.

Sample Input/Output

Input:
$per = array("name" => "Amit", "age" => 21, "gender" => "Male");
   
Output:
Array       
(
    [0] => name    
    [1] => age     
    [2] => gender  
)

PHP array_keys() Function Example 1

Array with and without containing keys.

<?php
$per = array("name" => "Amit", "age" => 21, "gender" => "Male");
print ("keys array...\n");
print_r (array_keys($per));

//array with out keys 
$arr = array("Hello", "world", 100, 200, -10);
print ("keys array...\n");
print_r (array_keys($arr));
?>

Output

The output of the above example is:

keys array...
Array       
(
    [0] => name    
    [1] => age     
    [2] => gender  
)
keys array...
Array       
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
) 

PHP array_keys() Function Example 2

Using value and strict mode.

<?php
$arr = array("101" => 100, "102" => "100", "103" => 200);

print("output (default function call)...\n");
print_r (array_keys($arr));    

print("output (with checking value)...\n");
print_r (array_keys($arr, 100));        

print("output (with checking value & strict mode)...\n");
print_r (array_keys($arr, 100, true));

?>

Output

The output of the above example is:

output (default function call)...
Array         
(             
    [0] => 101
    [1] => 102
    [2] => 103
)             
output (with checking value)...  
Array         
(             
    [0] => 101
    [1] => 102
)             
output (with checking value & strict mode)...
Array         
(             
    [0] => 101
)  

To understand the above examples, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.