0

I have an array with some measurement values that corresponds to different sensors. These measurements should be stored in my Measurements table. But I cannot form the variable name dynamically. => ${'request->AI' . '$counter'};

Any suggestions?

$this->validateWith([
                        'RecorderName' => 'required|string',
                        'Time' => 'required|date',
                        'AI1' => 'required|float',
                        'AI2' => 'required|float',
                        'AI3' => 'required|float',
                        'AI4' => 'required|float',
                        'AI5' => 'required|float',
                        'AI6' => 'required|float']);

$recorderSenor = Recorder::where('name', substr($request->RecorderName, 0, -4))->with('getSensorsRelation')->get();

$counter =1;

foreach ($recorderSenor as $sensor) {
            $measurement = new measurement();
            $measurement->sensor_id = $sensor->id;
            $measurement->value = ${'request->AI' . '$counter'};
            $measurement->timestamp = $request->time;
            $measurement->save();
            $counter++;
        }
vennot_be
  • 17
  • 4
  • 2
    `echo '$counter'` gives you `$counter` (not the value of $counter, see [this](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php)). Try `$request->{'AI' . $counter}` – Definitely not Rafal Jun 16 '21 at 14:46
  • This is what I was after. Leaving the `$request->` out of it made it work. Many thanks @DefinitelynotRafal How can I mark this as the right answer? – vennot_be Jun 16 '21 at 15:08

2 Answers2

0

There are couple ways to do this, but one easy way is to use concatenation.

        `$measurement->value = request()->AI . $counter;`
Kevin
  • 1,152
  • 5
  • 13
0

Correct answer was given by @DefinitelynotRafal in the comments.

echo '$counter' gives you $counter (not the value of $counter, see this). Try

$request->{'AI' . $counter}

vennot_be
  • 17
  • 4