How to translate a PHP app using array & function

How to translate a PHP app using array & function

It’s a good feature if your PHP app is multilingual because it makes the app future-proof. And that’s why every web app should have a translation system. If you are unfamiliar with the localization process, you might think it’s a hard job. There are a lot of ways to translate a PHP app. But in this article, I am going to describe the easiest procedure to translate a PHP app.

Before we start, let’s know the basic procedure we are going to follow. All we will use is a source array, containing strings of different languages and a function, which will do the translation from the source array. Another thing, this procedure can be followed in any type of app that is written in PHP. I am not using any framework or such thing, so you can modify it as per your need independently.

Enough talk. Let’s start.

The array that contains the translated strings

Save the below code in languages.php file.

// the array that contains all translated strings for Bangla language
$languages['bangla']['hi {username}, welcome to {app_name}!'] = 'হাই {username}, {app_name} এ আপনাকে স্বাগতম!';

// the array that contains all translated strings for Hindi language
$languages['hindi']['hi {username}, welcome to {app_name}!'] = 'नमस्ते {username}, {app_name} में आपका स्वागत है!';

You can also store different language arrays in different PHP files and later include them in the original PHP file.

The PHP function that will do the translation

Save the below code in function.php file.

function __($identifier, $echo = true, $data=''){
    // fetch language array
    global $languages;

    if(isset($languages[ACTIVE_LANGUAGE])){
        $lan = $languages[ACTIVE_LANGUAGE];
    }
    else{
        $lan = array();
    }
    $original_string = $identifier;
    $identifier = strtolower($identifier);

    $result = '';

    // select lan string using identifier
    if(isset($lan[$identifier])){
        $result = $lan[$identifier];
    }
    else $result = $original_string;

    // preparing data if it is string
    if(gettype($data) == 'string'){
        $prepared_data = array();
        if($data != ''){
            $array = explode(',', rtrim($data, ','));
    
            foreach($array as $value){
                list($p1, $p2) = explode(':', $value);
                $prepared_data[$p1] = $p2;
            }
        }
        $data = $prepared_data;
    }
    // placing data
    if(!empty($data)){
        $result = preg_replace_callback('/{(.*?)}/', function ($match) use ($data) {
            return isset($data[$match[1]]) ? $data[$match[1]] : $match[0];
        }, $result);
    }

    // return or echo
    if($echo) echo $result;
    else return $result;
}

Parameters

  1. $identifier string, required – The identifier is the index of the source array.
  2. $echo bool, optional, default value = true – Decides if the function will print the result or just return it.
  3. $data string or array, optional, default value = empty string – If you want to pass any data in the string, you can pass through this parameter.

Output

string – The translated string if a translation is available, otherwise the identifier string with the provided data.

How to translate the app using the function

// let's define the current active language 
define('ACTIVE_LANGUAGE', 'bangla');

// include array file and function file
require 'languages.php';
require 'function.php';


/** Example 1 */
$data = array(
    'username' => 'Anushka',
    'app_name' => 'DevsLib.'
);
__('Hi {username}, welcome to {app_name}!', true, $data);

// prints
// হাই Anushka, DevsLib. এ আপনাকে স্বাগতম!


/** Example 2 */
$translated_string = __('Hi {username}, welcome to {app_name}!', false, "username:Virat,app_name:DevsLib."); 
echo $translated_string;

// prints
// হাই Anushka, DevsLib. এ আপনাকে স্বাগতম!

What the function does

  1. First, it loads the $languages array, that contains all the translated strings.
  2. If ACTIVE_LANGUAGE is found inside $languages, stores the translation array in $lan. Otherwise, an empty array is stored.
  3. Converts the identifier string to lowercase letters for easy searching.
  4. Searches for the translated string in $lan variable using the identifier string.
  5. If found, stores it in the $result variable, otherwise, the original string is stored for further processing.
  6. If there is any data provided as a string, converts it to an associative array and stores it in $data.
  7. If there is any data to place in the $result string, search in $data and place the data in the $result string.
  8. Finally, prints or returns the $result.

What if there is no translation available for a string?

Well, this is not any rare thing. In such cases, the identifier string will be returned.

/** Example 3 */
__('There is no translation {empty_data}');

// prints
// There is no translation {empty_data}

Conclusion

This is it. As I have seen, this is the easiest way to translate a PHP web app. You can also add multi-language support feature in your app using gettext. What I have shown you here, is the basic phenomena of how this can be done. You can modify this function or the array as per your application structure. You can use cookies in your app for the definition of ACTIVE_LANGUAGE. You can use different language arrays in different language files and later include them separately.

All the files we have used here can be found in GitHub.

If you have any questions, do not hesitate to ask in the comment section. Thank you!

David Moss

Developer | Writer | Coffee lover

Leave a Reply