Welcome Guest, Not a member yet? Register   Sign In
variable name change in a loop
#1

[eluser]earlyriser[/eluser]
Hi.
I would like to change a variable name in a loop, from a view file but I cann't get it work.

My code is

Code:
<?=$row->keyword1?>,<?=$row->keyword2?>,<?=$row->keyword3?>,<?=$row->keyword4?>

&lt;?php for ( $counter = 1; $counter < 5; $counter++)
{    
    echo ${'row->keyword'.$counter};
}?&gt;

The first line is for testing purposes and it writes some keywords from the query results rows. It works fine.

With the FOR loop I want to have the same result, but I got and error:
Severity: Notice
Message: Undefined variable: row->keyword1

What is the correct way to do this? I have tried also
echo ${'$row->keyword'.$counter};
with the same error

Thanks.
#2

[eluser]roj[/eluser]
Would it not simply be echo $row->keyword.$counter within the loop?
#3

[eluser]earlyriser[/eluser]
[quote author="roj" date="1225169878"]Would it not simply be echo $row->keyword.$counter within the loop?[/quote]
Thanks for your reply roj, I also tried that, and I got the error:
Severity: Notice
Message: Undefined property: keyword
#4

[eluser]wr5aw[/eluser]
Maybe something like this:
Code:
&lt;?php for ( $counter = 1; $counter < 5; $counter++)
{    
    $keyword = 'keyword' . $counter;
    echo $row->$keyword;
}?&gt;
#5

[eluser]roj[/eluser]
Was going to add that too as it's essentially the same thing so i'm guessing it won't work either?

Question now: is the testing bit that works being executed in the same file as the loop? In the model, controller or view?
#6

[eluser]bigtimslim[/eluser]
Maybe this is a design problem and your db results should be filtered to 1-5 before they hit the view. What do the controller and model look like?
#7

[eluser]dmiden[/eluser]
Hi,
Use wr5aw's code.
Code:
$keyword = 'keyword'.$counter;
echo $row->keyword;
is not the same as
Code:
echo ${'row->keyword'.$counter};

Basically you can't use "->" in ${""}.
#8

[eluser]roj[/eluser]
Just for my own clarity: you could use

Code:
echo $row->keyword.$counter;

right?
#9

[eluser]dmiden[/eluser]
No. Not in the way you think.

Using the . will just merge them
e.g.

Code:
$this->var1 = 'foo';
$var2 = 'bar';
echo $this->var1.$var2; // outputs foobar

$this->var1 = '';
$var2 = 'bar';
echo $this->var1.$var2; // outputs bar

So it's basically $row->keyword . $counter;
and $row->keyword is empty, so it just echoes $counter.
#10

[eluser]roj[/eluser]
Ah, that's what i get for trying to be smart....!

Thanks for the clarity.




Theme © iAndrew 2016 - Forum software by © MyBB