Unless you know otherwise, I don’t think there is an easy way to directly set the internal pointer to a particular value, so using next() is not an effective way to get the next available letter. No problem, array elements can be accessed directly, like so:
$letter = $alphabet[$last_key+1];
Before doing that though, check if ( $last_key+1 == count( $alphabet ))
. If it is, the end of the alphabet has been reached and $last_key needs to be reset to -1 so when we add 1 to it, it gets the first element in the array at index 0.
You see, we are not using the internal pointer at all now. Instead, we are keeping track of the last array index used. No looping is required. Yes, you could reset the internal pointer, then do a loop of $last_key calls to next() to get to the right place, but there is no need. After getting the next letter from $alphabet, update the option to $last_key+1
Also, you don’t really need to initialize the option with add_option(). update_option() will add it if it does not already exist. So you start off your code with getting the option. We don’t yet know if it even exists at first, but we try to get it anyway.
Next, check if ( false === $last_key )
. If so, there is no saved value so initialize $last_key to -1, again so when we add 1 to it we get the first array value. To summarize:
get the option
if false comes back, set $last_key to -1
if $last_key has reached the alphabet end, reset $last_key back to -1
Assign to $letter the value extracted from $alphabet
update the option
return $letter