How To Use Array Keys Function With Example Using PHP

admin_img Posted By Bajarangi soft , Posted On 21-09-2020

We can get all the keys out of an associative array by using in-built function called array_keys() function.array_keys() function returns an array containing the keys.

get key value of an array in PHP

Syntax for array_keys() Function

array_keys(array, value, strict)


Parameter   Description

array    Specifies an input array
value   You can specify a value, then only the keys with this value are returned
strict  Used with the value parameter. Possible values:
            true - Returns the keys with the specified value.
            false - Default value. Not depending on type.


Example(1)​​​

$a=array("Kiran"=>"Mechanical engineering","Shiva"=>"Electrical ITI","Rajesh"=>"Computer Science");
print_r(array_keys($a));

above example in that we have array from that only we are displaying key values of array using array_key() function in PHP

Example(2)​​​
 
function get_Key($array) //using function
{
    $result = array_keys($array);
    return($result);
}

$array = array("one" => "Kiran", "two" => "Shiva", "three" => "Rajesh");
print_r(get_Key($array));
foreach (get_Key($array) as $key){
    echo "<h1>$key</h1>";
}

above example we created new array and function when we call function that time array element will pass through the get function from that only key elements will return using array_key() function

Complete code of array_key() function.
<!DOCTYPE html>
<html>
<head>
    <title>How to get key value of an array in PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <br>
    <br>
    <div class="text-center">
        <h1>PHP array_key() function </h1>
    </div>
    <br>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $a=array("Kiran"=>"Mechanical engineering","Shiva"=>"Electrical ITI","Rajesh"=>"Computer Science");
        print_r(array_keys($a));


        function get_Key($array)//using function
        {
            $result = array_keys($array);
            return($result);
        }

        $array = array("one" => "Kiran", "two" => "Shiva", "three" => "Rajesh");
        print_r(get_Key($array));
        foreach (get_Key($array) as $key){
            echo "<h1>$key</h1>";
        }

        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post