Dynamic variables? Not sure

I am working on a gallery for a multilingual website. Each language has it’s own directory en/filename.php and nl/filename.php but are using the same php file to display the gallery. The table gallery has the following two fields: description_en and description_nl. In order to echo the right description I have created a variable called lang ($lang=“en” and $lang=“nl”) in each directory. I am looking for a way to create some kind of dynamic variable, if you call it that way? Something like the following:


$lang = "en";
$gallery = $pdo->query (" SELECT description_en,  description_nl, photo FROM gallery ");
$description = "$gallery.description_$lang";

Is something like that or similar possible?

Thank you in advance

I tried the above but that isn’t working. After that I tried:


          $lang = "en";
	   $description = NULL;
	
	   $gallery->setFetchMode(PDO::FETCH_ASSOC);
	   while($row = $gallery->fetch()) {
	     $description = $row['description_$lang'];
		 echo $description;
	   }

But that isn’t working either.

Hi donboe,

If you want to use a variable as part of your array key, you have two choices:


// with a single quoted string
$description = $row['description_'.$lang];

// with a double quoted string
$description = $row["description_$lang"];

With a single quoted string, you have to use a . to concatenate the variable with the string, whereas when using double quotes, you can include the variable within the string and PHP will replace it with the value.

Thanks a lt fretburner :slight_smile: Great and helpful as usual

To my mind, you’d be better off storing the multiple language options in a table of their own:

image_id, language, description

With a compound primary key of image_id and language.

Or if you’ve got titles etc. as well in multiple languages then:

image_id, language, type, entry

with a compound key of image_id, language, type. Where type is: title, description etc.

That way, if you want to add more than nl and en in the future you don’t have to add more fields to the main table (which is bad design).

Hi Karl. I hear what you say and understand. Normally this would be my approach as well. Only this was an already existing website when I started to work on the site, so I left it this way. But thank you anyway.