As noted my comments on the original post, after fixing the missing bracket [assuming typo] in your array declaration, the function works correctly, if called correctly as echo lang['title']
. If you get a notice on Undefined index
, it means the $phrase
you're looking for doesn't exist in the $dict
array. [If you only get the notice in your error logs, you may want to turn on on-screen error reporting when
you're developing to catch these in real time!]
Basic debugging aside, let me help you tidy up this code a bit. First, $l
or language can be passed in as a function argument. Second, the $dict
doesn't need to be a variable, assuming you're not modifying it on the fly. You can declare it as a constant and avoid globals. Third, your array mapping is unnecessary overhead, when you can simply call the relevant indexes in the array. A minimal clean-up would then look something like
this:
const DICT = [
'title' => [
'en' => 'Welcome',
'de' => 'Willkommen'
],
'description' => [
'en' => 'Hello',
'de' => 'Hallo'
]
];
function lang[$phrase, $lang] {
// If you're using PHP 7, the null-coalescing operator is handy here:
return DICT[$phrase][$lang] ?? "Phrase {$phrase} Unknown!";
}
You'd use it like this:
// Sample usage: Output title in English and description in German:
echo lang['title', 'en'] . ' ' . lang['description', 'de'];
// Or, if the language variable is pre-defined, then e.g.:
$l = 'en';
echo lang['title', $l] . ' ' . lang['description', $l];
Here, the use of a constant for your dictionary is a basic but very efficient way to handle a global need for pre-defined data. Constants are parsed at compile-time, while variable declarations are parsed at runtime. They are available in all contexts. And you definitely don't want to have the whole $dict
inside your function just to avoid a global declaration!
A more elegant way to handle this would be to create a class, which will allow you to avoid the language function parameter. [Class constants and properties are like "local globals", available to all methods in the class.] Here's a sample application of your case as a class, where the dictionary is a class constant, and the language is a class property:
class Dict {
const DICT = [
'title' => [
'en' => 'Welcome',
'de' => 'Willkommen'
],
'description' => [
'en' => 'Hello',
'de' => 'Hallo'
]
];
public static $lang = 'en'; // for a default language
public static function phrase[$phrase]
{
return self::DICT[$phrase][self::$lang] ?? "Phrase {$phrase} Unknown!";
}
}
Dict::$lang = 'de'; // Define language
echo Dict::phrase['title'] . ' ' . Dict::phrase['description'];
// : Willkommen Hallo
If you expect to have a large dictionary that needs to be accessed in other contexts, or simply wish to centralize your language reference, then you may want to define it as a regular constant outside the class, as in the first example. I've used a class constant here mostly for educational purposes. Hope this helps you forward and towards cleaner code.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list [vector], hash table [an implementation of a map], dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.
Syntax
Specifying with array[]
An array
can be created using the array[] language construct. It takes any number of comma-separated key => value
pairs as arguments.
array[ key => value, key2 => value2, key3 => value3, ... ]
The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array[1, 2]
is preferred over array[1, 2, ]
. For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new
elements at the end.
Note:
A short array syntax exists which replaces
array[]
with[]
.
Example #1 A simple array
The key can either be an int or a string. The value can be of any type.
Additionally the following key casts will occur:
- Strings containing valid decimal ints, unless the number is preceded by a
+
sign, will be cast to the int type. E.g. the key"8"
will actually be stored under8
. On the other hand"08"
will not be cast, as it isn't a valid decimal integer. - Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key
8.7
will actually be stored under8
. - Bools are cast to ints, too, i.e. the key
true
will actually be stored under1
and the keyfalse
under0
. - Null will be cast to the empty string, i.e. the key
null
will actually be stored under""
. - Arrays and objects can not be used as keys. Doing so will result in a warning:
Illegal offset type
.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
Example #2 Type Casting and Overwriting example
The above example will output:
array[1] { [1]=> string[1] "d" }
As all the keys in the above example are cast to 1
, the value will be overwritten on every new element and the last assigned value "d"
is the only one left over.
PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays.
Example #3 Mixed int and string keys
The above example will output:
array[4] { ["foo"]=> string[3] "bar" ["bar"]=> string[3] "foo" [100]=> int[-100] [-100]=> int[100] }
The key is optional. If it is not specified, PHP will use the increment of the largest previously used int key.
Example #4 Indexed arrays without key
The above example will output:
array[4] { [0]=> string[3] "foo" [1]=> string[3] "bar" [2]=> string[5] "hello" [3]=> string[5] "world" }
It is possible to specify the key only for some elements and leave it out for others:
Example #5 Keys not on all elements
The above example will output:
array[4] { [0]=> string[1] "a" [1]=> string[1] "b" [6]=> string[1] "c" [7]=> string[1] "d" }
As you can see the last value "d"
was assigned the key 7
. This is
because the largest integer key before that was 6
.
Example #6 Complex Type Casting and Overwriting example
This example includes all variations of type casting of keys and overwriting of elements.
The above example will output:
array[7] { [1]=> string[1] "g" [-1]=> string[1] "d" ["01"]=> string[1] "e" ["1.5"]=> string[1] "f" [0]=> string[1] "h" [""]=> string[1] "j" [2]=> string[1] "l" }
Accessing array elements with square bracket syntax
Array elements can be
accessed using the array[key]
syntax.
Example #7 Accessing array elements
The above example will output:
string[3] "bar" int[24] string[3] "foo"
Note:
Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements [e.g.
$array[42]
and$array{42}
would both do the same thing in the example above]. The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Example #8 Array dereferencing
Note:
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an
E_WARNING
-level error message [E_NOTICE
-level prior to PHP 8.0.0] will be issued, and the result will benull
.
Note:
Array dereferencing a scalar value which is not a string yields
null
. Prior to PHP 7.4.0, that did not issue an error message. As of PHP 7.4.0, this issuesE_NOTICE
; as of PHP 8.0.0, this issuesE_WARNING
.
Creating/modifying with square bracket syntax
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets [[]
].
$arr[key] = value; $arr[] = value; // key may be an int or string // value may be any value of any type
If $arr doesn't exist yet or is set to null
or false
, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr
already contains some value [e.g. string from request variable] then this value will stay in the place and []
may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.
Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.
Note: As of PHP 8.1.0, creating a new array from
false
value is deprecated. Creating a new array fromnull
and undefined values is still allowed.
To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset[] function on it.
Note:
As mentioned above, if no key is specified, the maximum of the existing int indices is taken, and the new key will be that maximum value plus 1 [but at least 0]. If no int indices exist yet, the key will be
0
[zero].Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
The above example will output:
Array [ [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ] Array [ ] Array [ [5] => 6 ] Array [ [0] => 6 [1] => 7 ]
Array destructuring
Arrays can be destructured using the []
[as of PHP 7.1.0] or
list[] language constructs. These constructs can be used to destructure an array into distinct variables.
Array destructuring can be used in foreach to destructure a multi-dimensional array while iterating over it.
Array elements will be ignored if
the variable is not provided. Array destructuring always starts at index 0
.
As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified.
Array destructuring can be used for easy swapping of two variables.
Note:
The spread operator [
...
] is not supported in assignments.
Note:
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an
E_WARNING
-level error message [E_NOTICE
-level prior to PHP 8.0.0] will be issued, and the result will benull
.
Useful functions
There are quite a few useful functions for working with arrays. See the array functions section.
Note:
The unset[] function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values[] function.
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
Array do's and don'ts
Why is $foo[bar]
wrong?
Always use quotes around a string literal array index. For example, $foo['bar']
is correct, while $foo[bar]
is not. But why? It is common to encounter this kind of syntax in old scripts:
This is wrong, but it works. The reason is that this code has an undefined constant [bar
] rather than a string ['bar'
- notice the quotes]. It works because PHP
automatically converts a bare string [an unquoted string which does not correspond to any known symbol] into a string which contains the bare string. For instance, if there is no defined constant named bar
, then PHP will substitute in the string 'bar'
and use that.
Warning
The fallback to treat an undefined constant as bare string issues an error of level
E_NOTICE
. This has been deprecated as of PHP 7.2.0, and issues an error of level E_WARNING
. As of PHP 8.0.0, it has been removed and throws an Error exception.
Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.