Directly indexing an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
oz1cz
Forum Newbie
Posts: 5
Joined: Mon Nov 03, 2008 3:34 am

Directly indexing an array

Post 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
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Directly indexing an array

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Directly indexing an array

Post 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
There are 10 types of people in this world, those who understand binary and those who don't
oz1cz
Forum Newbie
Posts: 5
Joined: Mon Nov 03, 2008 3:34 am

Re: Directly indexing an array

Post by oz1cz »

Thank you for the information.
--
Claus
Post Reply