1

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

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;
    }  
}
Sign up to request clarification or add additional context in comments.

4 Comments

If you use $arrayAux[$color] ?? $color, then if the color isn't found, it will store the original color.
I edit, but I choose dont save any color if the key doesnt exist. But its a good idea, or save any other value.
In the original code, they have $frenshColors[] = $color; which is doing the same thing - if there isn't a translation then store the original.
Oh, its true, i didnt see it. Thanks!
1

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

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.