Create variable name from variable in loop (vanilla PHP)
I got myself a little bit cornered and I basically need this:
$i = 1;
while(true){
echo $object->name$i; //I need loop names ->name1 ->name2 ->name3
$i++;
}
In vanilla PHP.
How about put names in array, and loop the array.
$likesarray = ["biking", "jogging", "swimming", "baseball"];
foreach ($likesarray as $k => $v) {
echo $v;
echo "<br>";
}
You can also foreach over your object.
Also
echo $object->name$i;
Is wrong
It's
echo $object->name[$i];
- $object->name[0] is row 1
- $object->name[1] is row 2
- etc
Do you know how many there are beforehand?
I'm receiving data as:
$data->id1
$data->x1
$data->y1
$data->id2
$data->x2
$data->y2
$data->id3
$data->x3
$data->y3
But I don't know how many sets there are. So i want to do:
$i = 1;
while (true) {
if (isset($data->id$i)) {
$data->id$i
$data->y$i
$data->x$i
} else {
break;
}
$i++;
}
And creating variable as $data->x$i obviously doesn't work. (it's an illustration)
Always groups of 3, count rows and divide by 3.
The syntax is
$key = 'name'. $i;
$object->{$key};
But I believe it will throw an error if it does not exist
Please or to participate in this conversation.