Ryan
Ryan

Reputation: 1164

Using arrays with strings with a while loop

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']";

Upvotes: 1

Views: 64

Answers (1)

newfurniturey
newfurniturey

Reputation: 38436

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'];
// ...

Upvotes: 1

Related Questions