1

I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.

The code is as follows:

while ($i <= $numFields) {

    $type               = "\$field{$i}_Data['type']";
    $name               = "\$field{$i}_Data['name']";
    $placeholder        = "\$field{$i}_Data['placeholder']";
    $value              = "\$field{$i}_Data['value']";

    echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';

    $i++;

}

The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.

The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.

If any extra code/information is needed, feel free to ask.

Thank you.

NOTE - There is no physical PHP error, it's purely an error with this:

"\$field{$i}_Data['value']";
6
  • do you have n array named field1_Data with a variable of type ? Commented Sep 30, 2014 at 19:33
  • What did your error say exactly? Commented Sep 30, 2014 at 19:36
  • There is no physical PHP error, it's just that all fields created are text, and their names, values and placeholders are all "$field_Data[""]" with their alterations for each variable. I just wanted to know how I would join the array name with the $i variable to allow the multiple field process. Commented Sep 30, 2014 at 19:38
  • @Dagon, I have the correct variables, It's just an issue with how I am trying to get the value: "\$field{$i}_Data['value']"; Commented Sep 30, 2014 at 19:39
  • well i mjust confused and know thers got to be a better approach Commented Sep 30, 2014 at 19:41

1 Answer 1

1

There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.

Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):

$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...

However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:

$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...
Sign up to request clarification or add additional context in comments.

1 Comment

Working perfectly now! Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.