I have an array of english colors and I want to translate some of them to frensh, I didn't find a standard PHP function to replace some value of an array with other, So I wrote my own but I'm looking for a simpler way if there is!
I'm looping through the englishColors array and checking if there is the colors that I want to replace with frensh colors.
$englishColors = array("Black","Green","Red");
$frenshColors = array();
foreach ($englishColors as $color) {
if ($color == "Black") {
$frenshColors[] = "Noire";
continue;
}elseif ($color == "Red") {
$frenshColors[] = "Rouge";
continue;
}
$frenshColors[] = $color;
}
var_dump($frenshColors);
3 Answers 3
Use an array. In the index you write the english name, the value the french name.
$arrayAux = [
'red' => 'rouge',
'black' => 'noir',
];
Then, when you want the array with the french colors:
$frenshColors = array();
foreach ($englishColors as $color) {
if (array_key_exists($color, $arrayAux)) {
$frenshColors[] = $arrayAux[$color];
} else {
$frenshColors[] = $color;
}
}
4 Comments
$arrayAux[$color] ?? $color, then if the color isn't found, it will store the original color.$frenshColors[] = $color; which is doing the same thing - if there isn't a translation then store the original.Maybe use a hash-table kind of array?
$colors = [
"Black" => "Noire",
"Green" => "?",
"Red" => "Rouge",
];
echo $colors["Black"]; // Noire
Then if you want to the opposite, you can:
$colors = array_flip($colors);
echo $colors["Noire"]; // Black
Comments
if you only want to replace values in an array use: array_replace
https://www.php.net/manual/en/function.array-replace.php
If you want to translate the webpage as a whole look into GETTEXT https://www.php.net/manual/en/ref.gettext.php