1

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.

4

4 Answers 4

2
$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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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

$array[] = 'Hello World';
return array_keys($array, 'Hello World!');

1 Comment

Came back to this after a while. If you're looping through the array, then this is a good alternative to using end/key (since you don't want to reset the pointer). Using something like $keys = array_keys($array); $key = end($keys); to avoid the strict standards warning.
1

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

1 Comment

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
0

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!');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.