Home » PHP

PHP array_keys() function with example

PHP array_keys() function: Here, we are going to learn about the array_keys() function with example in PHP.
Submitted by IncludeHelp, on February 15, 2019

PHP array_keys() function

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:

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

Here,

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

Examples:

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

PHP code 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

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

PHP code 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

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
)  





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.