Hi I have a list of values named:
and I'd like to assign each value to an array element; something like:
$my_array[1]=$value1;
$my_array[2]=$value2;
$my_array[3]=$value3;
How can I do this using a for cycle? The array is not a problem but I can't figure out how to write some code for the value, it should be something like:
for($i=1; $i<=10000; $i++)
{
$my_array[$i]=$value$i;
}
Try this:
for ($i=1; $i<=10000; $i++) {
$val_name = "value" . $i;
$my_array[$i]=$$val_name;
}
You are almost there:
for($i=1; $i<=10000; $i++)
{
$my_array[$i] = $value;
}
Or this, if you want to append the counter as well:
for($i=1; $i<=10000; $i++)
{
$my_array[$i] = $value . $i;
}
What you are looking for are the {}.
$my_array[$i]=${'value'.$i};
for ($i = 1; isset(${"value$i"}); $i++) {
$my_array[$i] = ${"value$i"};
}
This syntax is known as variable variables.
You can use the $$
syntax:
for($i = 1; $i <= 10000; $i++) {
$name = 'value' . $i;
$my_array[$i] = $$name;
}