PHP: array_keys - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_map array_key_exists

Last updated: Sat, 27 Jan 2007

view this page in

# array_keys

(PHP 4, PHP 5)

array_keys -- Выбрать все ключи массива

## Описание

array array_keys ( array input [, mixed search_value] )

Функция array_keys() возвращает числовые и строковые ключи, содержащиеся в массиве `input`.

Если указан необязательный параметр `search_value`, функция возвращает только ключи, совпадающие с этим параметром. В обратном случае, функция возвращает все ключи массива `input`.

Пример 1. Пример использования array_keys()

`$array = array (0 => 100, "color" => "red");
print_r(array_keys ($array));
$array = array ("blue", "red", "green", "blue", "blue");
print_r(array_keys ($array, "blue"));
$array = array ("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large"));
print_r(array_keys ($array));`

Результатом выполнения вышеприведенной программы будет:

    Array
    (
        [0] => 0
        [1] => color
    )
    Array
    (
        [0] => 0
        [1] => 3
        [2] => 4
    )
    Array
    (
        [0] => color
        [1] => size
    )

> Замечание: Эта функция появилась в PHP 4. Ниже приведен ее эквивалент для PHP 3.

> Пример 2. Эквивалент функции array_keys() в PHP 3

> `function array_keys ($arr, $term="") {
> $t = array();
> while (list($k,$v) = each($arr)) {
> if ($term && $v != $term) {
> continue;
> }
> $t[] = $k;
> }
> return $t;
> }`

См.также array_values().

add a note User Contributed Notes
array_keys
master[at]request[dot]com
23-Feb-2007 03:14
`<?
// sample Array
$strArray=array(0=>"Apple",1=>"Chery");
foreach($strArray as $key=> $val){
echo $key ."-". $val[0];
}
?>
The output is
0 - Apple 1- Chery`
jason at ajax dot hk
06-Feb-2007 09:30
`just tested the following example on offical help, and found that the way array_keys() works have been changed
(it now correctly return all keys even through some values are identical)
<?
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
?>
----------------output start-------------------
Array
(
[0] => 0
[1] => 3
[2] => 4
)
-----------------output end--------------------
here's my code:
[code]
<?
$array = array("blue", "red", "green", "blue", "blue","blue", "blue");
echo '<br />source array<br />';
print_r($array);
echo '<br /><br />result of array_keys() <br />';
print_r(array_keys($array));
?>
[/code]
----------------output start-------------------
source array
Array
(
[0] => blue
[1] => red
[2] => green
[3] => blue
[4] => blue
[5] => blue
[6] => blue
)
result of array_keys()
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)
-----------------output end--------------------`
brettz9 a/- yah00 do/- com
22-Dec-2006 06:25
`Devmnky states that array_keys() doesn't work with multi-dimensional arrays. While it is true (as from his example), that array_keys does not recursively traverse the array for keys, one still can reference (or search for keys within) specific arrays within the array:
<?php
$array = array("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large"));
print_r(array_keys($array['color'], "blue")); // Correctly returns Array ( [0] => 0 ) (i.e., a new array starting at key 0, referring to the key of "blue" within the "color" array: 0)
?>`
Ray.Paseur sometimes uses GMail
21-Dec-2006 04:38
`Replace a key in an associative array, preserving the original order of keys and elements:
if (!function_exists('array_combine')) { // ONLY EXISTS IN PHP5
function array_combine($keys, $values) {
if (count($keys) != count($values)) {
return false; }
foreach($keys as $key) { $array[$key] = array_shift($values); }
return $array; }
} // END IF FUNCTION EXISTS
$keys = array_keys($array);
$values = array_values($array);
foreach ($keys as $k => $v) {
if ($v == "MANAGEMENT FEE CHARGE") { $keys[$k] = "MANAGEMENT FEES"; }
}
$array = array_combine($keys, $values);`
jochem
17-Feb-2006 04:13
`might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):
$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3");
echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n";
var_dump($r); print_r($r); var_export($r);
echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n";
var_dump("0","1",""," ");
OUTPUTS:
how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")
-----------
array(4) {
[0]=>
string(1) "0"
[1]=>
string(1) "1"
[""]=>
string(1) "2"
[" "]=>
string(1) "3"
}
Array
(
[0] => 0
[1] => 1
[] => 2
[ ] => 3
)
array (
0 => '0',
1 => '1',
'' => '2',
' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "`
Sven (bitcetera.com)
19-Dec-2005 06:43
`Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
<?php
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
// get the first key: returns 'first'
print array_shift(array_keys($array));
// get the last key: returns 'third'
print array_pop(array_keys($array));
// get the first value: returns '111'
print array_shift(array_values($array));
// get the last value: returns '333'
print array_pop(array_values($array));
?>`
vesely at tana dot it
09-Dec-2005 01:56
`The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".
<?php
$a = array("banana" => "yellow", "apple" = "red");
$k = get_some_fruit();
if (isset($a[$k]))
{
list($pos) = array_keys(array_keys($a), $k);
print "yes, we have {$k}s at position $pos\n";
}
?>
Not amazingly efficient, but I see no better alternative.`
alapidus
23-Nov-2005 05:07
`erwin at spammij dot nl, a far more efficient solution to your problem would be to use the array_map function:
<?php
$_POST = array_map('addslashes', $_POST);
?>`
ru dot dy at gmx dot net
14-Aug-2005 09:20
`I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array)
usage: array_remove(array $input [, mixed key ...])
<?php
function array_remove() {
if ($stack = func_get_args()) {
$input = array_shift($stack);
foreach ($stack as $key) {
unset($input[$key]);
}
return $input;
}
return false;
}
?>
Test:
<?php
$a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');
print_r($a);
print_r(array_remove($a, 'd', 'b', 5, 'sub'));
?>
Output:
Array
(
[a] => fun
[b] => 3.14
[sub] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[d] => what
[e] => xample
[5] => x
)
Array
(
[a] => fun
[e] => xample
)
Hope this helps someone.`
alex [@T] d-sn [D@T] com / Alex Galisteo
07-Aug-2005 02:46
`My version of PHP does not support the strict parameter. Moreover, I need a function that could make other comparsion different than equals and stricktly equals.
The funcition array_keys_advanced can make the following comparsions: equal, not equal, strictly greater than, equal or greater than, strictly less than, equal or less than.
<?php
if (!function_exists('array_keys_advanced')) {
//{{{ array_keys_advanced
/**
* Returns an array with the matching keys as values. A comparsion type can
* be spcified, even if it should be a strict comparsion or not.
* Note: It is not recursive.
*
* @param array $input
* @param string $search_value
* @param bool $strict
* @param string $comparison: {EQ | NEQ | GT | EGT | LT | ELT}
* @return Returns an array with the matching keys as values.
* @author alex [@T] d-sn [D@T] com // Alex Galisteo
*/
function array_keys_advanced() {
$nargs = func_num_args();
$arr = array();
$input = null;
$search_value = null;
$strict = (bool) false;
$comparison = "EQ";
$comparsion_types = array("EQ", "NEQ", "GT", "EGT", "LT", "ELT");
switch ($nargs) {
case 1:
$input = func_get_arg(0);
return array_keys($input);
break;
case 2:
$input = func_get_arg(0);
$search_value = func_get_arg(1);
return array_keys($input, $search_value);
break;
case 3:
$input = func_get_arg(0);
$search_value = func_get_arg(1);
$strict = (bool) func_get_arg(2);
$comparsion = "EQ";
break;
case 4:
$input = func_get_arg(0);
$search_value = func_get_arg(1);
$strict = (bool) func_get_arg(2);
$comparsion = strtoupper((string) func_get_arg(3));
$comparsion = (in_array($comparsion, $comparsion_types))?
$comparsion : "EQ";
break;
default:
return $arr;
break;
}
foreach ($input as $key => $val) {
if ($strict) {
if ($comparsion == "EQ" && $search_value === $val) {
$arr[] = $key;
}
elseif ($comparsion == "NEQ" && $search_value !== $val)
$arr[] = $key;
elseif ($comparsion == "GT" && $search_value > $val)
$arr[] = $key;
elseif ($comparsion == "EGT" && $search_value >= $val)
$arr[] = $key;
elseif ($comparsion == "LT" && $search_value < $val)
$arr[] = $key;
elseif ($comparsion == "ELT" && $search_value <= $val)
$arr[] = $key;
} else {
if ($comparsion == "EQ" && $search_value == $val)
$arr[] = $key;
elseif ($comparsion == "NEQ" && $search_value != $val)
$arr[] = $key;
elseif ($comparsion == "GT" && $search_value > $val)
$arr[] = $key;
elseif ($comparsion == "EGT" && $search_value >= $val)
$arr[] = $key;
elseif ($comparsion == "LT" && $search_value < $val)
$arr[] = $key;
elseif ($comparsion == "ELT" && $search_value <= $val)
$arr[] = $key;
}
}
return $arr;
}
//}}}
} //endif function_exists
?>`
webmaster [at] baz-x [dot] at
29-Jul-2005 03:43
`I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn't find a function I came up with my own solution.
I didn't find the propiest function to post to so I will post it here, hope you find it useful.
<?php
function array_extract($array, $extract_type = 1)
{
foreach ( $array as $key => $value )
{
if ( $extract_type == 1 && is_string($key) )
{
// delete string keys
unset($array[$key]);
}
elseif ( $extract_type == 2 && is_int($key) )
{
// delete integer keys
unset($array[$key]);
}
}
return $array;
}
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
Have fun with it.`
erwin at spammij dot nl
26-Jul-2005 05:28
`//'This will use the array_keys function to make all $_POST values addslashed.
$post_array_keys = array_keys($_POST);
for ($g=0;$g<count($post_array_keys);$g++) {
$_POST[$post_array_keys[$g]] = addslashes($_POST[$post_array_keys[$g]]);
}`
cristianDOTzuddas [AT] gmailDOTcom
06-Jul-2005 11:41
`The function extracts the key of an associative array from the position you need.
Input:
$arr = array('a'=>'first', 'b'=>'second', 'c'=>'third');
print(array_key($arr, 1));
Output: 'b'
<?
function array_key($arr, $pos) {
if (!empty($arr)) {
if ($pos===null)
$pos = 0;
$all_keys = array_keys($arr);
unset($arr);
$key = $all_keys[$pos];
unset($all_keys);
if (isset($key))
return $key;
else {
unset($key);
return null;
}
}
}
?>`
xorithNOSPAM (at) alsherok d.o.t net
26-May-2005 08:21
`Notes for steve and sip from below (wow, spanning years on these notes!)
First off, Steve is right - isset will *not* return true at all when checking for a key that has a value set to the built-in constant null.
Sip is right in that it is faster to use isset. However, however his facts seem a bit misleading. Let me show you my console output for my test:
[Notice] Populating test array with 200000 values...
[Notice] Setting key '100000' to null for null key test.
[array_key_exists] Starting timer...
[array_key_exists] Found key 150000, time: 0.00015640
[array_key_exists] Test Complete.
[isset] Starting timer...
[isset] Found key 150000, time: 0.00008583
[isset] Test Complete.
[array_key_exists:bad_key] Starting timer...
[array_key_exists:bad_key] Did not find bad key 400000, time: 0.00009155
[array_key_exists:bad_key] Test Complete.
[isset:bad_key] Starting timer...
[isset:bad_key] Did not find bad key 400000, time: 0.00008392
[isset:bad_key] Test Complete.
[array_key_exists:null_test] Starting timer...
[array_key_exists:null_test] Found key with null value 100000, time: 0.00008392
[array_key_exists:null_test] Test Complete.
[isset:null_test] Starting timer...
[isset:null_test] Did not find key with null value 100000, time: 0.00008392
[isset:null_test] Test Complete.
Yes, that's 200,000 values. I was using an md5 of microtime() and the index, to ensure that the data was of some sort of adequate size. I had to bump up my memory_limit to do the 200,00 index test.
One thing I'd like to note is I also tried this test with 2,000 and 20,000. What I found is that the times are almost identical all the way up to 200,000. The time is in seconds.
As you can see, while there is a significant time difference between array_key_exists and isset in the first test, the time appeared to improve down the board, until it was equal with isset in the last test. You might also note that really, the time isn't too bad, not for a function that will return a more accurate result than isset.
One more test, this time 500,000 indicies:
[Notice] Populating test array with 500000 values...
[Notice] Setting key '250000' to null for null key test.
[array_key_exists] Starting timer...
[array_key_exists] Found key 375000, time: 0.00016403
[array_key_exists] Test Complete.
[isset] Starting timer...
[isset] Found key 375000, time: 0.00008011
[isset] Test Complete.
[array_key_exists:bad_key] Starting timer...
[array_key_exists:bad_key] Did not find bad key 1000000, time: 0.00007629
[array_key_exists:bad_key] Test Complete.
[isset:bad_key] Starting timer...
[isset:bad_key] Did not find bad key 1000000, time: 0.00007629
[isset:bad_key] Test Complete.
[array_key_exists:null_test] Starting timer...
[array_key_exists:null_test] Found key with null value 250000, time: 0.00007439
[array_key_exists:null_test] Test Complete.
[isset:null_test] Starting timer...
[isset:null_test] Did not find key with null value 250000, time: 0.00007629
[isset:null_test] Test Complete.
Surprisingly, the times seem a tad shorter here. This could be a result of my server though, but the fact still stands that even with an incredibly large array, the time impact isn't a huge problem with array_key_exists.
So to wrap this up:
If you care to know if a key exists, even if it's null, use array_key_exists.
If you don't want to know if a key is there if it's null, use isset.
-- JWalker (Xorith)`
devmnky /at\ gmail /dot\ com
09-Mar-2005 06:03
`Please note that array_keys() does not work if you're trying to search for values within multi-dimensional arrays.
For example:
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array, "blue"));
will return:
Array
{
}`
steve at ukwebsystems dot com
25-Sep-2004 10:52
`note to sip at email dot ee
inefficent it may be, but it detects if array keys have been defined with null values.
with the array
$Row['field1'] = null;
$Row['field2'] = 'hello';
array_key_exists('field1',$Row) will return true
isset($Row['field1']) will return false, even though the key is present...`
sip at email dot ee
22-Aug-2003 05:33
`Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset($array[$key]), instead of array_key_exists($key, $array)
using isset() is usually about 1.3 times faster, according to my tests.`
rodrigo at NOSPAM dot dhweb dot com dot br
04-Feb-2003 04:39
`[Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it]
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don�t have control of depths.
<?php
function show_keys($ar){
echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";
foreach ($ar as $k => $v ) {
echo "<td align='center' bgcolor='#EEEEEE'>
<table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
" . $k . "
</font></td></tr></table>";
if (is_array($ar[$k])) {
show_keys ($ar[$k]);
}
echo "</td>";
}
echo "</tr></table>";
}
// Multidimensional array ->
$arvore = array();
$arvore['1'] = array();
$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3');
$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3');
$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3');
$arvore['2'] = array();
$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['3'] = array();
$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-
show_keys($arvore);
?>`
michielbakker at msn dot com
13-Nov-2002 09:45
`If you receive a bunch of variables and like to change most of them (or all of them for that matter), you can do something like this: (data has been sent to a page with POST)
<?
$allKeys = array_keys($HTTP_POST_VARS);
for ($i=0;$i<count($allKeys);$i++)
{
$$allKeys[$i] = strtoupper($HTTP_POST_VARS[$allKeys[$i]]);
}
?>
This makes caracters (a-z) uppercase. This is just one way to use it, ofcourse.
Hope this helps someone understand the way to use array_keys() or give any ideas. :)`
glennh at webadept dot net
13-Nov-2002 04:03
`All the cool notes are gone from the site.
Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
<?php
while (list($key, $value) = each
(${"HTTP_".$REQUEST_METHOD."_VARS"}))
{
echo $key." = ".$value." ";
}
?>`
jacob at keystreams dot com
20-Aug-2002 11:05
`Here is a way to use array_intersect on array keys rather than values:
<?php
$a = array("apple" => "red", "banana" => "yellow");
$z = array("apple" => "green", "peach" => "orange", "banana" => "rotten");
$intersected_keys = array_intersect(array_keys($a), array_keys($z));
print_r($intersected_keys);
?>
This will print:
Array ( [0] => apple [1] => banana )`
add a note
array_map array_key_exists

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST