Picking the Lock in PHP When you Don't Have a Key

There are times when you create an array based on a stream of incoming data, and in doing so, are blissfully (or not) ignorant of the keys. How do you get the first member from the array in that case?

For example, if I have an array based on user ID's, which looks like this:

$my_array = array(
13471 => array('first name' => 'Moe', 'last name' => 'Howard'),
15777 => array('first name' => 'Larry', 'last name' => 'Fine'),
24186 => array('first name' => 'Curly', 'last name' => 'Howard'),
33192 => array('first name' => 'Shemp', 'last name' => 'Howard')
);

Without knowing that the first key is 13471, and since it's not a numeric array with the first key being 0...what to do?

You might think that array_shift would be an option, but:

$x = array_shift($my_array)

yields

array('first name' => 'Moe', 'last name' => 'Howard')

without its key. There is a way to accomplish it in a similar manner, but it's messy, inefficient, and destructive to $my_array.

The simple approach is this:

reset $my_array;
$x[key($my_array)] = current($my_array);

The first line sets the pointer of the array to its first record. The second line retrieves the key of the current (first) record, and sets it as the key in $x, and then assigns the current record to that key.

Tags

Add new comment

Markdown

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Missing filter. All text is removed