Emil Orol
Emil Orol

Reputation: 561

PHP loop in object

I have 4 instances of the same object:

echo $payment->field_course_1_length[0]['value'];
echo $payment->field_course_2_length[0]['value'];
echo $payment->field_course_3_length[0]['value'];
echo $payment->field_course_4_length[0]['value'];

My question is so that I don't have to be typing the same over and over can I put it in a loop like this:

for ($i=1; $i<5; $i++) {

echo $payment->field_course_'$i'_length[0]['value'];

}

Thank you.

Upvotes: 0

Views: 87

Answers (3)

Cyclonecode
Cyclonecode

Reputation: 29991

You can do like this:

 for($i = 1;  $i <= 4; $i++) {
     echo $payment->{"field_course_".$i."_length"}[0]['value'];
 }

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

echo $payment->{"field_course_{$i}_length"}[0]['value'];

Upvotes: 3

KingCrunch
KingCrunch

Reputation: 131841

$tmp = $payment->{'field_course_' . $i . '_length'};
echo $tmp[0]['value'];

However, I strongly recommend to use arrays instead of dynamic properties. If they are not dynamic, don't access them dynamic.

Upvotes: 2

Related Questions