-1

I'm trying to initialize iterations of variables that i'm sending to my server-side script. I don't want to enter each of them individually so I am wondering if what I have is valid syntax or if there is a more efficient way of doing this.

for($i = 1; $i <=10; $i++){
  $itemNumber.$i = $_POST['title'.$i];
  $itemType.$i = $_POST['type'.$i];
  $itemDescription.$i = $_POST['description'.$i];
  $itemAmount.$i = $_POST['amount'.$i];
  $itemComments.$i = $_POST['comments'.$i];
}

My expected output is:

$itemNumber1 = $_POST['title1'];

$itemType1 = $_POST['type1'];

... after the first iteration and etc.

Jordan
  • 27
  • 6

1 Answers1

1

You can do this using PHP's Curly Brackets (Also called Complex Syntax)

for($i = 1; $i <=10; $i++){
    ${"itemNumber$i"} = $_POST["title$i"];
    ${"itemType$i"} = $_POST["type$i"];
    ${"itemDescription$i"} = $_POST["description$i"];
    ${"itemAmount$i"} = $_POST["amount$i"];
    ${"itemComments$i"} = $_POST["comments$i"];
}

But you really probably shouldn't, there is probably a much much better way to handle what you are trying to do.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71