key

(PHP 3, PHP 4, PHP 5)

key -- 从关联数组中取得键名

说明

mixed key ( array &array )

key() 返回数组中当前单元的键名。

例子 1. key() 例子

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

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if (
$fruit_name == 'apple') {
        echo
key($array).'<br />';
    }
    
next($array);
}
?>

参见 current()next()


add a note add a note User Contributed Notes
danny at dannymendel dot com
12-Apr-2006 11:41
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;
}
?>
php_notes at ionws dot com
11-Oct-2005 07:17
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
Danniel@t h e - police (d'0't) com
22-May-2005 04:55
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".
Danniel@t h e - police (d'0't) com
22-May-2005 04:55
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".
happy dot machine at skynet dot be
07-May-2003 02:20
$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);
shimon_d at hotmail dot com
25-Jan-2003 04:39
make array[a][b]
be    array[b][a]

function invertarray($a)
{
 $o=array();
 foreach($a as $k => $aa)
 {
  foreach($aa as $k1 => $v)
  {
   if(!isset($o[$k1]))$o[$k1]=array();
   $o[$k1][$k]=$v;
  }
 }
 return $o;
}
kajetan at kajetan dot nu
05-Jul-2002 04:20
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:

$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.
04-Jun-2002 08:13
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
mkeller at gmx dot de
12-Oct-2001 03:46
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...)

for($i = 0; $i <= 10; $i++) {
       $myarray[] = 'content '.$i;
       end($myarray);
       echo ('<br>key()='.key($myarray).' , content='.$myarray[$i]);
   }
php at snr-graphics dot com
24-Mar-2001 03:50
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.

<code sample begin>
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));
</end code sample>

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

$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.