0

I have the next situation, lets say i have an object with 10 attributes, named r1, r2, r3...r10. Now i want to extract the value of each attribute dynamically. for that i make a for like this and know it will work

$sum = 0;

for($i = 1; $i <= 10; $i ++){
$key = "r{$i}";
$sum += $this->$key;
}

This is a representative example, what i want to know is if instead of doing that, i could do something like

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

$sum += $this->r{$i};
}

and take the extra line off... i have tried several forms of concatenate this like that but i cant figure it out. Can any one tell me if it is possible and how.

emc
  • 47
  • 1
  • 5
  • where does r come from ? – Dave Jan 23 '14 at 15:45
  • they are attributes of the object... r1, r2, r3 ...r10...i call them like that just for the example, but it can be token1, token2, token3, how ever you like it,, the point is that the have all same name, with different numbers – emc Jan 23 '14 at 15:48
  • Please do some research prior to asking: http://stackoverflow.com/questions/1147937/php-curly-brace-syntax-for-member-variable – Alex Jurado - Bitendian Jan 23 '14 at 15:58

2 Answers2

1

That's because you don't use +=, use .= when concatenating :-)

Have a read of this: http://www.php.net/manual/en/language.operators.string.php

jskidd3
  • 4,609
  • 15
  • 63
  • 127
  • you can use += if you're doing a SUM of the values not wanting to just create a string. – Dave Jan 23 '14 at 15:45
  • 1
    @Dave Yes, but this question is related to concatenation (interconnecting of strings) – jskidd3 Jan 23 '14 at 15:46
  • no, im specifically askin for $this->r{$i}, how can i get the values of the attributes like that...this way wont work – emc Jan 23 '14 at 15:50
  • @emc Then you should edit your question to make what you're asking clearer – jskidd3 Jan 23 '14 at 15:51
0

You can do that :

$sum += $this->{'r'.$i};

Having multiples attributes named like that sounds like a problem for me. Why don't you use an array ?

Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
  • because the come form a form, they represent each input of the form, and thank you very much i have tried it already and it worked – emc Jan 23 '14 at 15:53
  • @emc Ok, but do you know you can use arrays in input names ? `r[3]` in your case). Anyway, if this helped, can you please accept my answer ? – Sebastien C. Jan 23 '14 at 15:57