Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get 1st value of an array (associative or not)

Tags:

arrays

php

This might sounds like a silly question. How do I get the 1st value of an array without knowing in advance if the array is associative or not?

In order to get the 1st element of an array I thought to do this:

function Get1stArrayValue($arr) { return current($arr); }

is it ok? Could it create issues if array internal pointer was moved before function call? Is there a better/smarter/fatser way to do it?

Thanks!

like image 722
Marco Demaio Avatar asked Feb 09 '10 15:02

Marco Demaio


1 Answers

A better idea may be to use reset which "rewinds array's internal pointer to the first element and returns the value of the first array element"

Example:

function Get1stArrayValue($arr) { return reset($arr); }

As @therefromhere pointed out in the comment below, this solution is not ideal as it changes the state of the internal pointer. However, I don't think it is much of an issue as other functions such as array_pop also reset it.
The main concern that it couldn't be used when iterating over an array isn't an problem as foreach operates on a copy of the array. The PHP manual states:

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.

This can be shown using some simple test code:

$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
    echo reset($arr) . " - " . $val . "\n";
}

Result:

a - a
a - b
a - c
a - d
like image 152
Yacoby Avatar answered Nov 10 '22 01:11

Yacoby