[SOLVED] how to create translate function as a method usable for an element in array

Issue

I have an array that has data about an exam, every exam has 1 type only from 4 types in all [iq,math,geo,gen] and I get it this way {{ $exam->type }} I only want to add translate method to the type, so when I write $exam->type->translate() I get the translated word, how the function structure would be and where should I write it, in Exam model or the controller of the page…

translate function:

function translate($word){
  return $word == "math" 
             ? "ماث" 
             : $word == "iq" 
             ? "آيكيو" 
             : $word == "geo"
             ? "هندسة"
             : $word == "gen"
             ? "شامل"
             : "غير معرّف"
}

Solution

Don’t nest ternaries like that. It’s a mess to read and to resolve since you easily will get the precedence wrong (plus, since PHP 7.4, you need to group nested ternaries with parentheses, or you’ll get a deprecation warning, or a fatal error from PHP 8)

If you rather do it manually (instead of using Laravel’s translation feature, which probably would be recommended), you can make it easier by using an array:

function translate($word)
{
    $words = [
        "math" => "ماث",
        "iq"   => "آيكيو", 
        "geo"  => "هندسة",
        "gen"  => "شامل",
    ];

    // Check if the word exists in the array and return it 
    // if it doesn't exist, return the default
    return $words[$word] ?? "غير معرّف";
}

Answered By – M. Eriksson

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.