Thursday, 16 October 2014

PHP: Get first key in a (possibly) associative array

What's the best way to determine the first key in a possibly associative array?

Solution:


<?php
$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'key3'); 
list($first_key) = each($arr);
print $first_key;   // key1

//another way


$first_key = current(array_flip($arr));
 print $first_key;  // key1

//another way


$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys   =   array_keys($yourArray);

echo "Key = ".$keys[0];    //Key = first_key


?>

0 comments:

Post a Comment