Jon Holm Jon Holm -4 years ago 95
PHP Question

If element is not in array to file

I am currently creating a site that will use multiple languages. The way I show the words/sentences is by echoing elements from an array. Right now it works fine, if the element is in the array, but it will show an "Undefined index"-error if it is not. So, I have to add the words to the array all the time, which I really do not want to.

Therefore, I wanted to know, if it is possible to make something like

  • if not in array, add 'requested' element to a txt file.


  • If undefined error add to a txt file.

Example of what I am doing right now:

<?php echo $lang["Address"]; ?>
//Notice: Undefined index: Address in ...

So, if I could get "Address" inserted into a txt file, it would be great. If it is not possible, then I need to add the words/sentences to the array every time I create a new text.

  • Maybe something like error logging, but where "Address" is the only thing that is logged?

Answer Source

Simplest translate function should help:


function __translate($name, $currentLang = 'en') {
    $path = sprintf("trans/%s.php", $currentLang);
    if (!file_exists($path)) {
        throw new Exception('No file for lang:' . $currentLang);
    $lang = include($path);
    if (isset($lang[$name])) {
         return $lang[$name];
    } else {
         file_put_content($currentLang . '_errors.txt', "\n\r". $name, FILE_APPEND);



return ['address' => 'Your address'];


// we don't have translation for address
return [];


<?php echo __translate["Address"]; ?>

Eventually, you can check some libraries for localization.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download