Page 1 of 1

Directly indexing an array

Posted: Fri Nov 06, 2009 7:23 am
by oz1cz
Consider this code:

Code: Select all

$greeting=array('en'=>'Hello', 'de'=>'Guten Tag', 'fr'=>'Bonjour');
echo $greeting[$lang];
If $lang is 'de', the code will output 'Guten Tag'.

I would like to create the array and index it in one statement. Something like this:

Code: Select all

echo array('en'=>'Hello', 'de'=>'Guten Tag', 'fr'=>'Bonjour')[$lang];
but this is illegal syntax.

Why is it illegal, and is there another way to achieve what I want without using a $greeting variable?

--
Claus

Re: Directly indexing an array

Posted: Fri Nov 06, 2009 7:46 am
by Eric!
It doesn't work because you are trying to echo a statement that does not return a value. array allocates a chunk of memory for your array data and sets up memory pointers to it which happens behind the scenes so to speak. It does not return any values from that array. As far as I know you have to declare it first then use it. I don't think there is a short cut. You could build a function that can define and return a value so when you echo it

echo sayhi($lang);

It esthetically looks like similar to what you want.

Re: Directly indexing an array

Posted: Fri Nov 06, 2009 7:59 am
by VladSun
How about declaring the whole "translations" array into a separate file and use it in a simple way like this:

Code: Select all

$translation = array(
    'en'    => array(
        'hello'    => 'Hello',
        'bye'     => 'Bye',
        ........
    ),
    'de'    => array(
        'hello'    => 'Guten Tag',
        'bye'     => 'DE Bye',
        ........
    ),
    .......
)

Code: Select all

function translate($lang, $item)
{
    return $translation[$lang][$item];
}

Code: Select all

echo translate($language, 'hello');
If you ever decide to put you translations into a DB, that will require to change only translate() function

Re: Directly indexing an array

Posted: Fri Nov 06, 2009 8:34 am
by oz1cz
Thank you for the information.
--
Claus