Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gust's avatar
Level 1

How to append a number to syntax

quiz app,I am trying to access my choice0,choice1,choice2,choice3 named inputs. But i need to make my $request->choice be $request->choice1`` for the first one and$request->choice2``` for the second and same for choice3 and choice4. But this does not work, How would I be able to do this

    public function update(Request $request, $id)
    {

        $question = Question::find($id);
        $question->question = $request->question;
        $i = 1;

        foreach ($question->choice as $choice) {
            $choicestring = "choice"+$i;
            $choice = $request->choicestring;
            dd($choice);
            $i++;
        }
    }
0 likes
4 replies
EventFellows's avatar

In php you need to use . instead of + to concatenate a string.

"choice" . $i; // instead of "choice" + $i

Or as an alertnative if you you have double quotes lie " you can just put your variable into the quotes like this.

$choicestring = "choice$i";
gust's avatar
Level 1

I have tried the .

    echo $request->choice1;

        foreach ($question->choice as $choice) {
            $choicestring = "choice".$i;
            echo $choicestring;
            $choice = $request->choicestring;
            dd($choice);
            $i++;
        }

I get the choice1 value when I access it normally thru $request->choice1. And echo $choicestring gives choice1 But when combined together which should be the equivalent of $request->choice1 the dd($choice) gives me null

Cronix's avatar

$choice = $request->$choicestring;

You left the $ off $choicestring.

Please or to participate in this conversation.