Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use array_shift() in PHP and get the key?

I have a list of files in an array where the filename is the key and the value is the last modified date in seconds. They are sorted from oldest to newest.

The files are glob()'d in, and then sorted this way using

asort($fileNameToLastModified, SORT_NUMERIC);

I use array_shift() to get the oldest file. Unfortunately, it seems to be giving me the value, and there doesn't seem to be a way to get the key.

Would the only way to do that be something like this?

$keys = array_keys($fileNameToLastModified);

$oldest = array_shift($keys);
array_shift($fileNameToLastModified); // to manually chop the first array member off too.

...or is there a built-in method to do it?

like image 436
alex Avatar asked Mar 08 '10 00:03

alex


3 Answers

$result = array_splice( $yourArray, 0, 1 );

... should do the trick. See array_splice.

like image 187
Decent Dabbler Avatar answered Oct 20 '22 11:10

Decent Dabbler


You could use each like:

$b = array(1=>2, 3=>4, 7=>3);
while(1) {
    list($key,$value) = each($b);
    if (empty($key))
        break;
    echo "$key $val\n";
}

Iterating the array with each will keep its last position.

like image 39
user1077365 Avatar answered Oct 20 '22 13:10

user1077365


Different approach:

list ($key, $value) = each($srcData); array_shift($srcData);

... (or just list($key)... if you doesn't need $value). See each and list.

Edit: As @ztate pointed in his comment, each() function have been deprecated so relying in this approach is no longer a good idea.

But I think similar behaviour can be approached by using the new key() function this (untested) way:

$key = key($srcData); $selected = array_shift($srcData);
like image 31
bitifet Avatar answered Oct 20 '22 12:10

bitifet