I have an array of available languages for my website, with a short ISO country code as the key for each language. I need to create a new array that contains the same info, but with numerical keys and where the first item in the new array is the current language.
I have this, which works fine:
$allLanguages = [
'en' => ['locale' => 'en_US', 'code' => 'en', 'displayName' => 'English'],
'sv' => ['locale' => 'sv_SE', 'code' => 'sv', 'displayName' => 'Swedish'],
'de' => ['locale' => 'de_DE', 'code' => 'de', 'displayName' => 'German']
];
$currentLanguage = 'sv';
// Create new numerical-ordered array with current language info as first element
$langugeList = [];
foreach( $allLanguages as $key => $value ){
if( $key == $currentLanguage )
array_unshift($langugeList, $value);
else
array_push($langugeList, $value);
};
Result:
array (
0 =>
array (
'locale' => 'sv_SE',
'code' => 'sv',
'displayName' => 'Swedish',
),
1 =>
array (
'locale' => 'en_US',
'code' => 'en',
'displayName' => 'English',
),
2 =>
array (
'locale' => 'de_DE',
'code' => 'de',
'displayName' => 'German',
),
)
Is there another, more elegant way of doing this?
I first had the idea to copy the array values and then sort them using usort()
(keeping the original order except for the current language), but that doesn't seem like an improvement to neither performance nor "elegancy".
I just realized that one option would be
$langugeList = [ $allLanguages[$currentLanguage] ];
foreach( $allLanguages as $key => $value ){
if( $key != $currentLanguage )
$langugeList[] = $value;
};