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?
$result = array_splice( $yourArray, 0, 1 );
... should do the trick. See array_splice.
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.
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);
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.
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.
Another possibility which is short working:
foreach ($array as $key => $value) break;
unset($array[$key]);
精彩评论