Femme Fatale
Femme Fatale

Reputation: 880

Loop for a variable in PHP

I have column named as r1_name, r2_name, r3_name in my table and .... I want to iterate them using for loop.

for($r=1; $r<=5; $r++) {  
    echo $data->r[$r]_name;// how am i going to iterate this
}

I get an error of:

syntax error, unexpected '_name'

Upvotes: 0

Views: 43

Answers (1)

Amal
Amal

Reputation: 76676

Use curly brace syntax:

for($r=1; $r<=5; $r++) {  
    echo $data->{"r{$r}_name"};
}

Or concatenation:

for($r=1; $r<=5; $r++) {  
    echo $data->{'r' . $r . '_name'};
}

Upvotes: 6

Related Questions