Php associative array for offset from 1 to 26
I am trying to create an associative array with alphabets as keys and 1 to 26 as values which I need to use to find the offset of alphabet from 1. So array['a'] would give me 1 and array['c'] would give me 3. Is there a way to declare such an array without typing in all ch开发者_Python百科aracters 1 by 1 as in
array('a' => 1, 'b' =>2, 'c'=>3 .... and so on
Or is there another way to get offset for alphabet from 1 to 26
You could do this using array_combine()
and range()
:
array_combine(range('a', 'z'), range(1, 26));
No need to build the array, use like following -
$index = ord($input_char) - ord('a') + 1;
You can use chr
and ord
:
chr(97); // a
chr(122); // z
ord('a'); // 97
ord('z'); // 122
arr = array();
for($i=1; $i<=26; ++$i) {
arr(chr(96+$i)) = $i;
}
精彩评论