It should be noted that the inverse function to keys (which converts keys to values) is array_count_values (which converts values to keys). This is needed to use things like array_intersect_key. Could go in several places. Took me a while to figure it out.
array_keys
(PHP 4, PHP 5)
array_keys — Return all the keys or a subset of the keys of an array
Description
array_keys() returns the keys, numeric and
string, from the input array.
If the optional search_value is specified,
then only the keys for that value are returned. Otherwise, all
the keys from the input are returned.
Parameters
-
input -
An array containing keys to return.
-
search_value -
If specified, then only keys containing these values are returned.
-
strict -
Determines if strict comparison (===) should be used during the search.
Return Values
Returns an array of all the keys in input.
Changelog
| Version | Description |
|---|---|
| 5.0.0 |
Added the strict parameter.
|
Examples
Example #1 array_keys() example
<?php
$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));
?>
The above example will output:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)
See Also
- array_values() - Return all the values of an array
- array_key_exists() - Checks if the given key or index exists in the array
- array_search() - Searches the array for a given value and returns the corresponding key if successful
anthony at berglas dot org
03-Apr-2012 12:32
Na'ven Enigma
10-Mar-2012 01:41
I was trying to figure out how to normalize an array with numerical keys. Since I was doing for() for a lot of things, but only replacing it if the conditions were right, I wound up with off ball arrays I couldn't access. That being said, I looked for a method of normalizing the array and couldn't find one, so I built my own. I'm not sure how to go about making it recursive, but I didn't need that feature for my own, so I just went without recursion.
//This will take array([5] => "test1", [4] => "test2", [9] => "test3") into array([0] => "test1", [1] => "test2", [2] => "test3") so you can access it easier.
function normalize_array($array){
$newarray = array();
$array_keys = array_keys($array);
$i=0;
foreach($array_keys as $key){
$newarray[$i] = $array[$key];
$i++;
}
return $newarray;
}
qeremy [atta] gmail [dotta] com
05-Mar-2012 11:50
Simple ways to prefixing arrays;
<?php
function array_keys_prefix($arr, $pref = "") {
$rarr = array();
foreach ($arr as $key => $val) {
$rarr[$pref.$key] = $val;
}
return $rarr;
}
function array_keys_prefix_multi($arr, $pref = "") {
$rarr = array();
foreach ($arr as $key => $val) {
$rarr[] = array_keys_prefix($val, $pref);
}
return $rarr;
}
// $a = array("foo" => "FOO", "bar" => "BAR", "baz" => "BAZ"); // or
$a = array("foo" => "FOO", "bar" => "BAR", "baz" => array(1,2,3));
print_r(array_keys_prefix($a, "my_"));
// db fetch...
$products = array(
array("id" => 1, "name" => "Foo"),
array("id" => 2, "name" => "Bar")
);
print_r(array_keys_prefix_multi($products, "product_"));
?>
Array
(
[my_foo] => FOO
[my_bar] => BAR
[my_baz] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => Foo
)
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
)
izzecold at live dot de
10-Jan-2012 03:21
<?php
/* A Function created by myself for checking multiple array keys
For Example u got an Array like $_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.
*/
function mKeyChecker($arr,$keys=array()) {
if(count($keys) > 1) {
$valid_keys = 0;
foreach($keys as $key) {
if(array_key_exists($key,$arr)) $valid_keys++;
}
if($valid_keys == count($keys)) {
return true;
} else {
return false;
}
} else if(count($keys) == 1) {
if(array_key_exists($key[0],$arr)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
// Execution Example
if(mKeyChecker($_SESSION,array('id','user','email','type'))) {
echo "is!";
} else {
echo "not!";
}
?>
craig1231 at hotmail dot com
21-Dec-2011 09:41
A needed a function to find the keys which contain part of a string, not equalling a string...
<?php
function array_keys_contain($input, $search_value, $strict = false)
{
$tmpkeys = array();
$keys = array_keys($input);
foreach ($keys as $k)
{
if ($strict && strpos($k, $search_value) !== FALSE)
$tmpkeys[] = $k;
elseif (!$strict && stripos($k, $search_value) !== FALSE)
$tmpkeys[] = $k;
}
return $tmpkeys;
}
?>
el dot quick at gmail dot com
23-Sep-2011 03:23
Sorry for my english...
I wrote a function to get keys of arrays recursivelly...
<?php
function recursive_keys($input, $search_value = null){
$output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input)) ;
foreach($input as $sub){
if(is_array($sub)){
$output = ($search_value !== null ? array_merge($output, recursive_keys($sub, $search_value)) : array_merge($output, recursive_keys($sub))) ;
}
}
return $output ;
}
?>
I hope it will be usefull
Regards
pat dot leblanc at gmail dot com
29-Aug-2011 09:05
It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
for example:
<?php
$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);
foreach(array_keys($importantKeys) as $key){
echo gettype($key)."\n";
}
?>
will return on a 64 bits system:
<?php
integer
string
?>
but on a 32 bits system:
<?php
string
string
?>
I hope it will save someone the huge headache I had :)
rarioj at gmail dot com
04-Oct-2009 01:38
Sometimes we want to find out the last added numerical key right after we use " array_push($array, $value) " or " $array[] = $value ". This can be achieved by calling:
<?php
return array_pop(array_keys($array));
?>
ferrerna at gmail dot com
23-Jan-2009 03:14
Here's a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
<?php
function array_collapse($arr, $x, $y) {
$carr = array();
while ($el = current($arr)) {
$carr[ $el[$x] ] = $el[$y];
next($arr);
}
return $carr;
}
?>
Example usage (pseudo-database code):
<?php
$query = db_query('SELECT name, value FROM properties');
$result = db_returnAll($query);
/* This will return an array like so:
[
['name' -> 'color', 'value' -> 'blue'],
['name' -> 'style', 'value' -> 'wide-format'],
['name' -> 'weight', 'value' -> 3.6],
['name' -> 'name', 'value' -> 'Waerdthing']
]
*/
$propArr = array_collapse($result, 'name', 'value');
/* Now this array looks like:
[
['color' -> 'blue'],
['style' -> 'wide-format'],
['weight' -> 3.6],
['name' -> 'Waerdthing'],
*/
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
nodarinodo at mail dot ru
03-Dec-2008 05:35
<?php
//It's a way to get keys from values )
$es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");
foreach(array_values($es) as $ess){
echo $ess." =>";
for($i =0; $i < count(array_keys($es, $ess)); $i++){
echo reset(array_keys($es, $ess))."<BR>";
} }
?>
neil at 11 out of 10
23-Jul-2008 07:10
<?php
/*
* This function will return the keys of elements in the
* haystack where the value is found in array needle
*/
function array_value_intersect_keys( $array_haystack, $array_needle ){
$intersected = array_intersect( $array_haystack, $array_needle );
return array_keys( $intersected );
}
// usage
$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );
$array_needle = array( 2, 8 );
$array_keys_of_intersecting_values = array_value_intersect_keys( $array_haystack, $array_needle );
print_r( $array_keys_of_intersecting_values );
?>
returns
Array
(
[0] => 1
[1] => red
)
edsongarrido at gmail dot com
12-Jun-2008 12:46
/*
*
*This function will return a .csv from a given array inside the $_SESSION['my_array']
*
*$csv_name -> the name we want the csv has to
*$download -> true or false to download the csv file after done
*
*/
<?php
function createCSV($csv_name, $download) {
$i = 1;
$csv = "";
/* erase the old file, if it exists */
@unlink("../../csv/" . $csv_name . ".csv");
/* array is in a session variable
* this may be useful to avoid many db queries if it is the case */
$my_array = $_SESSION['my_array'];
/* how many fields has the given array */
$fields = count(array_keys($my_array[0]));
/* extracting the titles from the array */
foreach(array_keys($my_array[0]) as $title)
{
/* array_keys percurs the title of each vector */
$csv .= $title;
/* while it is not the last field put a semi-colon ; */
if($i < $fields)
$csv .= ";";
$i++;
}
/* insert an empty line to better visualize the csv */
$csv .= chr(10).chr(13);
$csv .= chr(10).chr(13);
/* get the values from the extracted keys */
foreach (array_keys($my_array) as $tipo)
{
$i = 1;
foreach(array_keys($my_array[$tipo]) as $sub)
{
$csv .= $my_array[$tipo][$sub];
if ($i < $fields)
$csv .= ";";
$i++;
}
$csv .= chr(10).chr(13);
}
/* export the csv */
$export_csv=fopen("../../csv/". $csv_name .".csv", "w+");
fwrite($export_csv, $csv);
fclose($export_csv);
/* download the csv */
if ($download == true)
header('Location:' . "../../csv/" . $csv_name . ".csv");
exit();
}
?>
Hayley Watson
04-Oct-2007 01:43
An alternative to RQuadling at GMail dot com's array_remove() function:
<?php
function array_remove(array $array, $value, $strict=false)
{
return array_diff_key($array, array_flip(array_keys($array, $value, $strict)));
}
?>
RQuadling at GMail dot com
27-Mar-2007 11:31
If you want to remove a value from an array, then there is no direct mechanism.
The following function uses the array_keys() function to find the key(s) of the value that you want to remove and then removes the elements for that key.
I've also given some examples and the output.
<?php
/**
* array array_remove ( array input, mixed search_value [, bool strict] )
**/
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
$a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
foreach($a_Keys as $s_Key) {
unset($a_Input[$s_Key]);
}
return $a_Input;
}
?>
Beside scalar variables (integers, floats, strings, boolean), you can also use arrays as the values you want to remove.
<?php
// Results in array(8, 8.0, '8', '8.0')
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8));
// Results in array(8, 8.0, '8', '8.0', array('8'))
array_remove(array(8, 8.0, '8', '8.0', array(8), array('8')), array(8), True);
?>
creator at mindcreations dot com
19-Mar-2007 08:12
This function will extract keys from a multidimensional array
<?php
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
?>
Example code:
<?php
$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),
"size" => array("small", "medium", "large"));
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
?>
Example output:
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
Ray.Paseur sometimes uses GMail
20-Dec-2006 10:38
Replace a key in an associative array, preserving the original order of keys and elements:
<?php
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 10: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):
<?php
$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 12: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
08-Dec-2005 07: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.
ru dot dy at gmx dot net
14-Aug-2005 04: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
06-Aug-2005 09: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 10: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.
sip at email dot ee
22-Aug-2003 12: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 10: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 03: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)
<?php
$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
12-Nov-2002 10: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 06: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 )
