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

search for in the

krsort> <in_array
[edit] Last updated: Fri, 24 May 2013

view this page in

key

(PHP 4, PHP 5)

keyRetourne une clé d'un tableau associatif

Description

mixed key ( array &$array )

key() retourne la clé courante dans le tableau array.

Liste de paramètres

array

Le tableau.

Valeurs de retour

La fonction key() retourne simplement la clé de l'élément du tableau qui est actuellement pointée par le pointeur interne. Cette fonction ne modifie en aucun cas la position de ce pointeur. Si le pointeur interne pointe un élément se situant après la fin de la liste des éléments, ou bien si le tableau est vide, la fonction key() retournera NULL.

Exemples

Exemple #1 Exemple avec key()

<?php
$array 
= array(
    
'fruit1' => 'apple',
    
'fruit2' => 'orange',
    
'fruit3' => 'grape',
    
'fruit4' => 'apple',
    
'fruit5' => 'apple');

// Cette boucle affiche toutes les clés
// dont la valeur vaut "apple"
while ($fruit_name current($array)) {
    if (
$fruit_name == 'apple') {
        echo 
key($array).'<br />';
    }
    
next($array);
}
?>

L'exemple ci-dessus va afficher :

fruit1<br />
fruit4<br />
fruit5<br />

Voir aussi

  • current() - Retourne l'élément courant du tableau
  • next() - Avance le pointeur interne d'un tableau



krsort> <in_array
[edit] Last updated: Fri, 24 May 2013
 
add a note add a note User Contributed Notes key - [20 notes]
up
1
FatBat
1 year ago
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset
($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
up
0
B. Keil
17 days ago
A little warning regarding a trap I fell into:

"foreach()" loops have no effect on the output of this situation. The documentation of "foreach()" says:

"As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior. "

Whatever that is supposed to mean, it does not use the internal array pointer in a way that you could read the current position with "key()". The following two loops are NOT equivalent:

<?php
$array
= array('a', 'b', 'c');
foreach (
$array as $value) {
    echo
key($array)." => $value\n";
}

echo
"\n";
foreach (
$array as $key => $value) {
    echo
"$key => $value\n";
}
?>

Output:
1 => a
1 => b
1 => c

0 => a
1 => b
2 => c
up
0
michael
4 years ago
Here is an improved version of the KeyName function below. It is simpler and faster, especially on large arrays as it runs in O(1) instead of O(n).

<?php
function KeyName(array $a, $pos) {
   
$temp = array_slice($a, $pos, 1, true);
    return
key($temp);
}
?>

Also, KeyName($a, -1) will return the last key, etc.
up
0
yarco dot w at gmail dot com
5 years ago
Re: br_joris[at]hotmail[doth]com

Do you really mean you want 2 keys point to 1 value?
What you've written seems you want 1 key point to 2 values.

But if you really want 2 keys point to 1 value, you could do the following:

<?php
$buf
['key1'] = 'abc';
$buf['key2'] = & $buf['key1'];
?>
up
-1
happy dot machine at skynet dot be
10 years ago
<?php
$tab
= array();
$tab[0] = 'php';
$tab[1] = '.';
$tab[2] = 'net';

// you will not enter the while
// $key = 0, while will consider $key as false
reset($tab);
while (
$key = key($tab) ) {
echo
$tab[$key];
next($tab);
}

// this will
reset($tab);
while (!
is_null($key = key($tab) ) ) {
echo
$tab[$key];
next($tab);
}

// when key() can't return a 'key', it return NULL
echo var_dump($key);
?>
up
-2
HellFireAE at gmail dot com
1 year ago
I've used this as a way of getting $_GET's from the URL. It's actually quite cool, I don't know if this is a hack or what but I like it.

<?php
 
switch(strToLower(key($_GET))){
    case
"register":
     
$page->set("{PAGE_TITLE}", "Register");
      break;
    default:
     
$page->set("{PAGE_TITLE}", "Play");
      break;
  }
?>

So if you put "?register" it outputs the page title to "Register" and if it isn't that, then it's "Play".

Hope this helps people.
up
-2
Twey
5 years ago
As of PHP5, objects are passed by reference by default.
up
-2
php_notes at ionws dot com
7 years ago
Note that key($array) returns NULL if $array's internal pointer goes past the end of the array.  For example, the following code:

<?php
$arr
= array(
   
'one' => '1',
   
'two' => '2',
   
'three' => '3',
   
'four' => '4',
   
'five' => '5');

for (
$i = 0; $i < 10; $i++) {
   
var_dump(key($arr));
   
next($arr);
}
?>

results in:
string(3) "one"
string(3) "two"
string(5) "three"
string(4) "four"
string(4) "five"
NULL
NULL
NULL
NULL
NULL
up
-3
kajetan at kajetan dot nu
10 years ago
I'm writing a forum and use an array to hold all the smiles. The keys in the array are the characters to write to get a smiley, and the data is the filename, like this
$Smiles[':-)'] = 'smile.gif'

To output all the smileys in a table with 3 columns, I wrote this code:

<?php
$the_end
= false;

$s = reset($Smiles);
$k = key($Smiles);

while(!
$the_end){
    echo
'<tr>';
    for(
$i=0; $i<3; $i++){
        echo
'<td>';
        if(
$the_end) echo '&nbsp;';
        else{
        echo
$k.'< br><img src="'. $s .'">';
         
$s = next($Smiles);
        if (
$s==false) $the_end=true;
        else
           
$k = key($Smiles);
        }
        echo
"</td>\n";
    }
    echo
"</tr>\n";
}
?>

I had to write a space in the < br> tag in the code above, because the board did a line brake otherwise.
up
-5
mkeller at gmx dot de
11 years ago
In the case key() does not give you back the key(myarray) but "0", try this:
(Try this example without the line containing "end($myarray)" and you see my reason for this post...)

<?php
for($i = 0; $i <= 10; $i++) {
       
$myarray[] = 'content '.$i;
       
end($myarray);
        echo (
'<br>key()='.key($myarray).' , content='.$myarray[$i]);
    }
?>
up
-2
B. Keil
16 days ago
@FatBat
Your solution is elegant in that it is swift and short - only two commands.

However, performance wise it's not ideal to sort an array to get the key of the highest value. I have written a test case with three examples - yours, another, sophisticated function that allows to pass your own compare function and a third, optimized for performance.

<?php
error_reporting
(E_ALL|E_STRICT);
function
key_of_max_val(array $array, $cmpFunction = null) {
        if (
$cmpFunction === null) $cmpFunction = create_function('$a,$b', 'return $a > $b;');
        if (!
function_exists($cmpFunction)) {
               
trigger_error(
                       
is_string($cmpFunction) ?
                               
"Did not find function '".mb_substr($cmpFunction, 0, 20)."'" :
                               
"String reference to function expected for \$cmpFunction\n",
                       
E_USER_WARNING
               
);
                return
null;
        }
       
$maxKey = key($array);
        foreach (
$array as $key => $value)
                if (
$cmpFunction($value, $array[$maxKey]) > 0)
                       
$maxKey = $key;
        return
$maxKey;
}

function
key_of_max_val2(array $array) {
       
$maxVal = reset($array);
       
$maxKey = key($array);
        foreach (
$array as $key => $value) {
                if (
$value > $maxVal) {
                       
$maxKey = $key;
                       
$maxVal = $value;
                }
        }
        return
$maxKey;
}

function
key_of_max_val3(array $array) {
       
arsort($array);
        return
key($array);
}

$array = array('nadine', 'Natasha', 'Nina', 'nicole');
echo
$array[key_of_max_val($array)]."\n";
echo
$array[key_of_max_val($array, 'strcasecmp')]."\n";
echo
$array[key_of_max_val2($array)]."\n";
echo
$array[key_of_max_val3($array)]."\n";

$array = array();
for(
$i = 0; $i < 1000000; $i++) $array[] = rand(0, 1024*1024);

foreach(array(
'key_of_max_val', 'key_of_max_val2','key_of_max_val3') as $function) {
       
$before = microtime(true);
       
$key = $function($array);
       
$after = microtime(true);
       
printf("%s returned key %d referring to %d after %.2f seconds.\n", $function, $key, $array[$key], $after - $before);
}
?>

Results:
$ php example.php
nicole
Nina
nicole
nicole
key_of_max_val returned key 360688 referring to 1048575 after 0.87 seconds.
key_of_max_val2 returned key 360688 referring to 1048575 after 0.16 seconds.
key_of_max_val3 returned key 360688 referring to 1048575 after 1.65 seconds.

However, function 2 has the disadvantage of actually changing the internal array pointer, since it's call-by-reference. If you do that in a foreach loop over $array you're in trouble. Without the reference a typical result is 0.25 seconds.
up
-2
goker.cebeci
1 year ago
object usage:

<?php

$object
= new stdClass();
$object->child->key = 'value';

echo
key((array) $object->child);
// key

?>
up
-2
FokeyJoe
2 years ago
Just to illustrate the behaviour of the internal pointer when you add items. Adding to an array does not affect the internal pointer.

<?php
$a
= array();
var_dump(key($a));  // null
$a[] = "jump";
var_dump(key($a));  // 0
$a[] = "lazy";
var_dump(key($a));  // 0
end($a);
var_dump(key($a));  // 1
$a[] = "fox";
var_dump(key($a));  // 1
?>
up
-2
Dallas at ekkysoftware dot com
3 years ago
I had a problem when there are nulls in your data, such as:-

<?php
$row
= array(  'first'=>'number', 'second'=>'letter', 'third'=>null, 'forth'=>'word');

while(
$value = current($row)){
    echo
"\"".key($row)."\"";
   
next($row);
}
?>

The problem is that current() returns the value 'null', but it isn't the end of the list. To get the correct results I used:-

<?php
foreach($row as $value){
    echo
"\"".key($row)."\"";
   
next($row);
}
?>
up
-2
danny at dannymendel dot com
7 years ago
An auto incremental key value function, returning the key value:

<?
function add_key ($value, $array) // returns the key of the value added or existing already within the array
{
    if (
is_array ($array))
    {
        if (!
in_array ($value, $array))
        {
           
ksort ($array);

           
end ($array);

           
$key = key ($array) + 1;

           
$array[$key] = $value;
        }
        else
        {
           
$key = array_search ($value, $array);
        }
    }
    else
    {
       
$key = 1;

       
$array[$key] = $value;
    }
    return
$key;
}
?>
up
-2
Danniel@t h e - police (d'0't) com
8 years ago
To get the key name by position from Array:
<?php
$myArray
['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo(
$myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
  
// $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

  
if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return
"NULL"// set this any way you like

  
reset($myArray);
   for(
$i = 0;$i < $pos; $i++) next($myArray);

   return
key($myArray);
}

echo
KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".
up
-2
php at snr-graphics dot com
12 years ago
A Method of Multi-Dimensionalizing an Associative Array (This idea was designed with Graphics (image filenames in mind):

(A quick overview):
While working on a rather large web application, I found that I needed a way to obtain "all" the details on images used by the application, these images (by filename) were stored in the configuration file, in the form of associative arrays.

The following represents an example of how I tool those and converted them into multi-dimensional associative arrays.

<?php
do {
 
$size = getImageSize($path.$myarray[key($myarray)]);
  if (
$size[2] == '1') { $size[2] = 'gif'; }
  else if (
$size[2] == '2') { $size[2] = 'jpg'; }
  else if (
$size[2] == '3') { $size[2] = 'png'; }
  else if (
$size[2] == '4') { $size[2] = 'swf'; }
  else {
$size[2] = 'UNKNOWN'; }
$myarray[key($myarray)] = Array($myarray[Key($myarray)],$size[0],$size[1],$size[2],$size[3]);
} while (
next($myarray));
?>

The end result is an multi-dim. associative array which contains the values:

<?php
$myarray
["this"][0] = # filename.gif
$myarray["this"][1] = # width
$myarray["this"][2] = # height
$myarray["this"][3] = # type (converted to the file extension.)
$myarray["this"][4] = # height=x width=x
?>

This may not be all that impressive to some, but it turned out to be very useful for me, so I thought I'd share, in addition, I think it gives a "very" good example of "a use" for the Key() function.

Frankly, I was quite happy to discover this function, I can't count the number of times I "needed to use the key as a value".

I hope you find this code useful.
up
-3
jamon at clearsightdesign dot com
3 years ago
I wrote a simple, yet powerful function for finding a key in an array relative to another key. This is very useful for finding the next key in an associative array if you know the current key, or any other arbitrary key relative to the current key.

This function does not use a foreach loop. I have not tested it for speed compared to a foreach loop. I would assume it's faster since it uses PHP's built in functions, but I could be wrong. I'd appreciate feedback on this.

- Jamon Holmgren

<?php
   
// array_key_relative - Returns a key in an associative array relative to another key without using foreach. Very useful for finding previous key or finding next key in array, etc
    // - Written by Jamon Holmgren (www.jamonholmgren.com). Last revised 8/18/2009. Free for any use.
    // function array_key_relative(array $array, string $current_key, int $offset)
   
function array_key_relative($array, $current_key, $offset = 1) {
       
// create key map
       
$keys = array_keys($array);
       
// find current key
       
$current_key_index = array_search($current_key, $keys);
       
// return desired offset, if in array, or false if not
       
if(isset($keys[$current_key_index + $offset])) {
            return
$keys[$current_key_index + $offset];
        }
        return
false;
    }
?>

Usage example:

<?php
    $test_array
= array(
       
"apple" => "Red, shiny fruit",
       
"orange" => "Orange, dull, juicy fruit",
       
"pear" => "Usually green and odd-shaped fruit",
       
"banana" => "Long yellow fruit that monkeys like to eat",
       
"cantelope" => "Larger than a grapefruit",
       
"grapefruit" => "Kind of sour"
   
);
   
    echo
array_key_relative($test_array, "apple", 2); // outputs "pear"
   
echo array_key_relative($test_array, "orange", -1); // outputs "apple" */

   
$next_key = array_key_relative($test_array, "banana", 1); // Get the key after banana (cantelope)
   
echo $test_array[$next_key]; // outputs "Larger than a grapefruit"
?>
up
-4
egingell at sisna dot com
5 years ago
What's the point of lines 14 and 25? $array is destroyed when the function returns. If you want this to work as written, change line 2 to this: (pass $array by reference instead of by value)
<?
function add_key ($value, &$array) // returns the key of the value added or existing already within the array
?>

>    danny at dannymendel dot com
>    12-Apr-2006 09:41
>    An auto incremental key value function, returning the key value:
>   
> 1    <?
> 2    function add_key ($value, $array) // returns the key of the value added or existing already within the array
> 3    {
>
4        if (is_array ($array))
>
5        {
>
6            if (!in_array ($value, $array))
>
7            {
>
8                ksort ($array);
>
9   
>10                end ($array);
>
11   
>12                $key = key ($array) + 1;
>
13   
>14                $array[$key] = $value;
>
15            }
>
16            else
>
17            {
>
18                $key = array_search ($value, $array);
>
19            }
>
20        }
>
21        else
>
22        {
>
23            $key = 1;
>
24   
>25            $array[$key] = $value;
>
26        }
>
27        return $key;
>
28    }
>
29    ?>
up
-4
Danniel@t h e - police (d'0't) com
8 years ago
To get the key name by position from Array:
<?php
$myArray
['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;

echo(
$myArray[1]);   /* return NULL */
/* isset($myArray[1]) return false;   */
/* is_null($myArray[1]) return true;  */

function KeyName($myArray,$pos) {
  
// $pos--;
   /* uncomment the above line if you */
   /* prefer position to start from 1 */

  
if ( ($pos < 0) || ( $pos >= count($myArray) ) )
         return
"NULL"// set this any way you like

  
reset($myArray);
   for(
$i = 0;$i < $pos; $i++) next($myArray);

   return
key($myArray);
}

echo
KeyName($myArray,1);  // result: name2
echo KeyName($myArray,2);  // result: name3
echo KeyName($myArray,3);  // result: "NULL"
?>

You can get any existing "key name" from array that is located at position $pos gived as second parameter. If no element is defined at given position the function will return the string "NULL".

 
show source | credits | stats | sitemap | contact | advertising | mirror sites