1

I have array like this:

[0] =>
   ['lang'] => 'DE',
   ['message'] => 'some text'
[1] =>
   ['lang'] => 'EN',
   ['message'] => 'some text'
[2] =>
   ['lang'] => 'NZ',
   ['message'] => 'some text'
[3] =>
   ['lang'] => 'CH',
   ['message'] => 'some text'

and clause like this if $lang = 'NZ' not found then find and return message for $default_lang = 'DE', else return message for 'NZ'

my realization:

foreach($res_arr as $key => $value) {
    if ($res_arr[$key]['lang'] == $lang) {
        return $res_arr[$key]['message'];
    }
}

foreach($res_arr as $key => $value) {
    if ($res_arr[$key]['lang'] == $default_lang) {
        return $res_arr[$key]['message'];
    }
}

is there any better way to do this?

1
  • Quick idea: If possible, create the array to have the language codes as keys. Then you can check if there is an entry for the specific language in your array. Commented Oct 25, 2011 at 13:10

2 Answers 2

3

Try with:

$lang = ''; // lang param
$default_lang = 'DE';
$languages = array(
  'DE' => 'some text',
  'EN' => 'some text',
  'NZ' => 'some text',
  'CH' => 'some text'
);

if ( !isset($languages[$lang]) ) {
  $lang = $default_lang;
}
$message = $languages[$lang];

Edit

Way to transform your array into my $languages array:

$languages  = array();
$your_array = array( /* your data */ );

foreach ( $your_array as $val ) {
  $languages[ $val['lang'] ] = $val['message'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is the fastest method I know this, but firstly I somehow should transform my array into yours and I dunno how to do this.
0

I'm a doubtful whether array_search will work here i.e. on multi-dimenstional array. Anyways, here is my solution:

$default_lang_msg = '';
foreach($res_arr as $key => $value) {
    if ($res_arr[$key]['lang'] == $lang) {
        return $res_arr[$key]['message'];
    }
    else if ($res_arr[$key]['lang'] == $default_lang) {
        $default_lang_msg = $res_arr[$key]['message'];
    }    
}

return $default_lang_msg;

btw array with language code as keys is the way to go if you can afford to change the same.

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.