Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is a simple method to return the array key when using array[] to add new values.

For example:

$array[] = 'Hello World';
return $Key_of_Hello_World;

The method I'm thinking of involves:

$key = count($array)-1;

Is there a different solution?

Conclusion

A combination of end() and key() is the best in general as it allows for associative but if your array only uses numerical keys, count()-1 seems to be the simplest and just as fast. I added this to the other linked question.

share|improve this question
    
1  
end($array); $key = key($array); –  Sean Mar 10 at 5:16
1  
possible duplicate of PHP get index of last inserted item in array –  Patrick Evans Mar 10 at 5:16
    
Thanks Patrick. I must have just not searched hard enough. –  Devon Mar 10 at 5:27
add comment

4 Answers

up vote 2 down vote accepted
$array[] = 'Hello World';
end($array); // set internal pointer to end of array
$key = key($array); // get key of element where internal pointer is pointing at
return $key;
share|improve this answer
    
This appears to be the fastest solution, although requiring two lines of code. Another solution suggested in the other thread was $key = end(array_keys($array)); which is a tiny bit slower but only requires one line. I'm still pondering whether count-1 will work well enough though as it seems just as fast as this method but obviously wouldn't work with associative like this would. –  Devon Mar 10 at 5:31
add comment

You can do something like this too..

<?php

function printCurrKey(&$array)
{
    return array_keys($array)[count($array)-1];
}

$array[] = 'Hello World';
echo printCurrKey($array);// "prints" 0
$array[] = 'This is a new dimension !';
echo printCurrKey($array);// "prints" 1
$array['newkey'] = 'Hello World is has a new key !';
echo printCurrKey($array);// "prints" newkey
share|improve this answer
1  
Yes for using the [] it seems count-1 may be the best method. Only requires one line and is extremely fast. array_search can be a bit slower with larger arrays but it is a interesting method. +1 –  Devon Mar 10 at 5:33
add comment

you want to use array_keys: http://us1.php.net/manual/es/function.array-keys.php

$array[] = 'Hello World';
return array_keys($array, 'Hello World!');
share|improve this answer
add comment

you can use array_keys() for return keys of an array

return array_keys($array)

for individual key try to use

return array_keys($array, 'Hello World!');
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.