PHP array_keys example

PHP array_keys() Function

PHP array_keys() Function is an inbuilt function in PHP and return the array of keys from the another given array. Given array may be associative array (key – value) pairs or indexed array. This function return an array.

Syntax

array array_keys ($array, $search_value, $strict)

PHP array keys Function

$array (required): This argument refers to the main array in which you want to fetch the keys.

$search_value (optional): If this argument is passed then function will return the keys corresponding to this element otherwise it will return all the keys of the array.

$strict (optional): If this argument is true then strict comparison will be used during the search otherwise it has false as default value.

Return Value: This function will return an array of keys like indexed array.

Example 1

<?php
$arr = array("james" => 15, "david" => 18, "smith" => 34);
print_r(array_keys($arr));
?>

Output

Array 
( 
 [0] => james 
 [1] => david 
 [2] => smith 
)

Example 2

<?php
$arr = array("david","james","john","smith");
print_r(array_keys($arr));
?>

Output

Array 
( 
 [0] => 0 
 [1] => 1 
 [2] => 2 
 [3] => 3 
)

In the below program, passed the search value along with given array. Now it will return only those keys who has the search value.

Example 3

<?php
$arr = array("david","james","david","john","smith","david");
$search_value = "david";
print_r(array_keys($arr,$search_value));
?>

Output

Array 
( 
 [0] => 0 
 [1] => 2 
 [2] => 5 
)

More Related Post

 

Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.

Leave a comment

Your email address will not be published. Required fields are marked *

0 0 0
FOLLOW ON