Re: How do I get the first element's key of an array of objects?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Daevid Vincent wrote:
I have an array of objects in PHP5. Each element's key is the database row
ID.

I don't see a graceful way of finding the first element's key ID.

So I have this...

Array
(
    [3] => fooObject Object
        (
            [id:protected] => 3
            [model:protected] => ABC
            [read:protected] => public
            [write:protected] => private
        )
    [5] => fooObject Object
        (
            [id:protected] => 5
            [model:protected] => DEF
            [read:protected] => public
            [write:protected] => private
        )
)


Etc.

I want to get [3] somehow.

http://www.php.net/manual/en/function.array-pop.php
array_pop() pops and returns the last value of the array, shortening the
array by one element.
Which is opposite of what I want.

http://www.php.net/manual/en/function.array-shift.php
Shift an element off the beginning of array But this reduces the array :(


My hack is to do this:

	foreach($fooObject as $key => $object)
	{
		$id = $key;
		break;
	}

There has to be a better way. Something more elegant?


How about reversing the array...

http://us4.php.net/manual/en/function.array-reverse.php

And then you can use array_pop()

OR

foreach ( $myArray as $key => $value ) {
	$theOneIWant = $value;
	break;
}

--
John C. Nichel
ÜberGeek
KegWorks.com
716.856.9675
john@xxxxxxxxxxxx

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux