how could this situation be solved best?
Well, you seem to want to perform a value replacement, so create a lookup and access the appropriate replacement by its key.
Do not bloat your script with a switch
block, just create a lookup array, then replace while iterating your rows of data. You can use an iterating function or a simple foreach()
loop.
Code: (Demo) (Modern syntax since PHP7.4)
$enToCz = [
'Monday' => 'Pondělí',
'Tuesday' => 'Úterý'
];
$data = [
['tutor_name' => 'John Doe', 'course_day' => 'Monday',],
['tutor_name' => 'John Doe', 'course_day' => 'Tuesday',]
];
array_walk(
$data,
function (&$row) use ($enToCz) {
$row['course_day_cz'] = $enToCz[$row['course_day']];
}
);
/* or you can use:
foreach ($data as &$row) {
$row['course_day_cz'] = $enToCz[$row['course_day']];
}
*/
var_export($data);
Output:
array (
0 =>
array (
'tutor_name' => 'John Doe',
'course_day' => 'Monday',
'course_day_cz' => 'Pondělí',
),
1 =>
array (
'tutor_name' => 'John Doe',
'course_day' => 'Tuesday',
'course_day_cz' => 'Úterý',
),
)
Explanation of syntax:
&
before a variable means "modify by reference" (that is the term to search if you want to do some more research). It allows the data held in the variable to be directly mutated. This is necessary when a "copy of a variable" is being accessed.
There is some rather informative chatter at PHP foreach change original array values.
use()
is a technique used to transfer global variables into the scope of a custom function (closure).
In PHP, what is a closure and why does it use the "use" identifier?
Also array_map()
can be used to return an array with the additional column without needing to declare a result array or modifying the original array. (Demo)
var_export(
array_map(
fn($row) => $row + ['course_day_cz' => $enToCz[$row['course_day']]],
$data
)
);