Tuesday, 14 August 2018

How to get the first element of an associative array in PHP

I've been always wondering how to get the first element of an associative array in PHP.

For numeric keys you could just do $arr[0] but it'll a little bit different for associative arrays.
Solutions
$arr = array('one' => 'hello', 'two' => 'world');
Solution #1
reset($arr);
list ($key1, $val1) = each($arr);
Solution #2
$i = 0;
foreach ($arr as $key => $value) {
    if (++$i == 1)
        echo $key;
        break;
    }
}
Solution #3
reset($arr);
echo key($arr);  
Solution #4
reset($arr);
echo @array_shift(array_keys($arr)); 
Suppressing Warnings such as:
Debug Strict (PHP 5): PHPDocument1 line 6 - Only variables should be passed by reference
Solution #5
reset($arr);
echo end(array_keys(array_reverse($arr))); 

0 comments:

Post a Comment