array_keys()是PHP中的一个内置函数,用于返回数组的所有键或键的子集。
语法:
array array_keys(input_array,search_value, $strict)
参数:该函数采用三个参数,其中一个为必需参数,另外两个为可选参数。
$input_array(必需):指向我们要操作的数组。
$search_value(可选):指向我们要搜索数组的元素的值。如果传递此参数,则函数将仅返回与该元素对应的键,否则将返回数组的所有键。
$strict(可选):决定在搜索期间是否应使用严格比较(===)。默认值为false。
返回值:该函数返回一个数组,其中包含输入数组的所有键或键的子集,具体取决于传递的参数。
示例:
Input : $input_array = ("one" => "shyam", 2 => "rishav",
"three" => "gaurav")
Output :
Array
(
[0] => one
[1] => 2
[2] => three
)
Input : $input_array = ("one", "two", "three", "one",
"four", "three", "one", "one")
$search_value = "one"
Output :
Array
(
[0] => 0
[1] => 3
[2] => 6
[3] => 7
)
在下面的程序中,我们将一个简单的关联数组传递给array_keys()函数,以打印其所有的键:
<?php
// PHP function to illustrate the use of array_keys()
function get_Key($array)
{
$result = array_keys($array);
return($result);
}
$array = array("one" => "shyam", 2 => "rishav",
"three" => "gaurav");
print_r(get_Key($array));
?>
output:
Array
(
[0] => one
[1] => 2
[2] => three
)
在下面的程序中,除了数组外,我们还传递了一个值,该值只返回键位置。
<?php
// PHP function to illustrate the use of array_keys()
function get_Key($array, $search_value)
{
$result = array_keys($array, $search_value);
return($result);
}
$array = array("one", "two", "three", "one", "four",
"three", "one", "one");
$search_value = "one";
print_r(get_Key($array, $search_value));
?>
output:
Array
(
[0] => 0
[1] => 3
[2] => 6
[3] => 7
)