Mading Ne Mading Ne - 17 days ago 5
PHP Question

Referencing class properties dynamically

for ($e = 1; $e <= 10; $e++)
{
$edd = Setting::where('id', '=', $e)->update([
'nama' => $request->nama1,
'isi' => $request->isi1,
]);
}


How can I dynamically reference class properties within the
for
loop? I want to reference
nama1
and
isi1
up to
nama10
and
isi10
on the
$request
object.

Answer
for ($e = 1; $e <= 10; $e++)
{
    $edd = Setting::where('id', '=', $e)->update([
      'nama' => $request->{"nama$e"},
      'isi'  => $request->{"isi$e"},
    ]);
}

For more readability, you might want to do this:

$request->{"nama{$e}"} // Notice the inner braces around $e