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

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

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

 asort($fileNameToLastModified, SORT_NUMERIC); 

I use array_shift () to get the oldest file. Unfortunately, this seems to give me meaning, and there seems to be no way to get the key.

Would there be a single way to do it 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 for this?

+6
sorting arrays php
source share
6 answers
 $result = array_splice( $yourArray, 0, 1 ); 

... should do the trick. See array_splice .

+13
source share

You can use each as:

 $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 contain its last position.

+3
source share

Different approach:

 list ($vlid, $selected) = each($srcData); array_shift($srcData); 

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

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

But I think that this behavior can be approached with the new key() function this (unverified) way:

 $vlid = key($srcData); $selected = array_shift($srcData); 
+2
source share

You can 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 performance works, so you may need profiling, but it will probably be faster than array_keys() for large arrays, since it does not need to array_keys() over everything.

0
source share

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

I'm not sure if you are going to actually get more key / value pairs from the array. Therefore, I will not go into details about what else you need to do.

0
source share

Another feature that works short:

 foreach ($array as $key => $value) break; unset($array[$key]); 
0
source share

All Articles