PHP Tutorial - PHP array_keys() function






Definition

The array_keys() function returns an array of all the keys in that array.

Syntax

PHP array_keys() function has the following syntax

array array_keys ( array arr [, mixed value [, bool strict]] )

Parameter

ParameterIs RequiredDescription
arrRequired.Array to search
valueOptional.Only the keys with this value are returned
strictOptional.Used with the value parameter.

Possible values for strict:

ValueDescription
trueCheck type. the number 9 is not the same as the string "9".
falseDefault value. Not checking type, the number 9 is the same as the string "9".

By default, this is done by checking each key's value with the == operator (is equal to); however, if you specify 1 as the third parameter, the check will be done with === (identical to).





Example

Get all keys in an array


<?php
    $users[0] = 'PHP';
    $users[1] = 'Java';
    $users[2] = 'java2s.com';
    $userids = array_keys($users);
    print_r($userids);
?>

The code above generates the following result.

Example 2

Using the value parameter:


<?php
    $a=array("p"=>"PHP","j"=>"java2s.com","a"=>"Apple");
    print_r(array_keys($a,"java2s.com"));
?>

The code above generates the following result.





Example 3

Using the strict parameter, false:


<?php
    $a=array(10,20,30,"10");
    print_r(array_keys($a,"10",false));
?>

The code above generates the following result.

Example 4

Using the strict parameter, true:


<?php
    $a=array(10,20,30,"10");
    print_r(array_keys($a,"10",true));
?>

The code above generates the following result.