views:

57

answers:

3

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?

Thanks

+5  A: 
$result = array_splice( $yourArray, 0, 1 );

... should do the trick. See array_splice.

fireeyedboy
I ended up just keeping what I had, because with this I still need to do an `array_keys()` and get an array member. But this is still another way to do it, so I'll accept it :)
alex
A: 

You could also do this:

<?php

$arr = array('a' => 'first', 'b' => 'second');

// This is your key,value shift line
foreach($arr as $k => $v) { break; }

echo "Key: $k\nValue: $k";

This will output:

Key: a
Value: first

I'm not sure how the performance is, so you might want to do some profiling, but it's likely to be faster than array_keys() for large arrays, since it doesn't need to iterate over the whole thing.

Sam Minnée
Since it copies the whole `$arr`, I'd say it could be terrible on big arrays.
zneak
`foreach()` shouldn't copy the array, surely?
Sam Minnée
A: 

You can take a look at key() current() or each(). They do what you asked for.

I'm not really sure if you intend to actually get more key/value pairs from the array afterwards. So I won't get into any details of what else you might need to do.

chris