Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hi Larry,

 

I haven't been on the forum in a while - what I have learned from your books so far has kept me going nicely.

 

But I needed to create a whole slew of PHP variables with similar names and came across the ability to create them dynamically.  In case it is of interest to forum readers, here's my code (from a MySQL select result):

while (list($var1, $var2, $var3, $var4) = mysqli_fetch_row($result))
{
    ${"title_" . $var1 . "_" . $var2} = $var3 . ", " . $var4;
}

This creates PHP variables of the form $title_n_m where 'n' will be the value of $var1 and 'm' will be the value of $var2.

 

Works like a treat - I was quite amazed!

 

All the best from Oz, Cheers.

 

Link to comment
Share on other sites

Thanks for sharing that! For what it's worth, there are situations in which dynamic variables are a real life-saver, but I almost always find an array to be a cleaner, more foolproof solution. Just a thought...

 

Hope you're doing well!

Link to comment
Share on other sites

Hi Larry,  Nice to hear from you.

 

Yes, I first tried to use an array construct but the heredoc echo I am using would not resolve the array elements.  Then I tried creating the PHP variables one by one and while that worked it was cumbersome.  I think I found the dynamic variables info in stack overflow almost by accident but I can't remember exactly (I'll put that down to my septuagenarian years :-)

 

Again, cheers from Oz.

Link to comment
Share on other sites

Further to the above, when I try and use an array, I get an 'array to string conversion error' which is not there if I use a dynamically generated variable.

 

The test code is (within a heredoc echo):

<tr>
    <td><a href="$large_1_1", title="$title_array[1][1]"><img src="$icon_1_1</a></td>
    <td><a href="$large_1_2", title="$title_1_2"><img src="$icon_1_2</a></td>
</tr>

The array variable for the first title gives me the error, the dynamic variable for the second title works fine. Can you see what I'm doing wrong with the array approach?

 

And this post facility won't let me copy and paste code between the

and

tags.

 

Thanks in anticipation for your insights.

 

Cheers

 

Oops I missed the closing quotes and '>' in the src-es - they are there in the code.

Edited by Necuima
Link to comment
Share on other sites

 Share

×
×
  • Create New...