translate.php
Table of Contents
Functions
- translate() : mixed
- Retrieve the translation for a specific language, with optional fallback to a default language.
Functions
translate()
Retrieve the translation for a specific language, with optional fallback to a default language.
translate(array<string, mixed>|object|null $fields[, string|null $lang = null ][, string|null $default = null ]) : mixed
This version is safer: if the requested language and the fallback are missing, it returns null
instead of returning the full array/object.
Example usage:
$translations =
[
'fr' => 'Bonjour',
'en' => 'Hello',
'es' => 'Hola'
];
translate( $translations , 'en' ); // 'Hello'
translate( $translations , 'de' , 'fr' ); // 'Bonjour' (fallback)
translate( $translations , 'it' , 'de' ); // null
translate( $translations ); // ['fr' => 'Bonjour', 'en' => 'Hello', 'es' => 'Hola']
$translationsObj = (object) $translations ;
translate( $translationsObj , null ) ; // (object) ['fr' => 'Bonjour', 'en' => 'Hello', 'es' => 'Hola']
Parameters
- $fields : array<string, mixed>|object|null
-
Array or object of translations keyed by language codes.
- $lang : string|null = null
-
Desired language code. If null, returns all translations.
- $default : string|null = null
-
Optional fallback language code if
$langis missing.
Tags
Return values
mixed —Returns the translation for the requested language, the fallback, all translations (if $lang is null), or null if no match.