Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andyandy's avatar

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.

0 likes
6 replies
jlrdw's avatar

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
Sinnbeck's avatar

Do you know how many there are beforehand?

andyandy's avatar

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)

jlrdw's avatar

Always groups of 3, count rows and divide by 3.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

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.