View Single Post

  #10 (permalink)  
Old 05-08-2008
Rik Wasmus
 
Posts: n/a
Default Re: For loop question?

On Thu, 08 May 2008 21:05:03 +0200, SM <servandomontero@gmail.com> wrote:

>
>
> I have a couple of arrays that represent different categories. One
> array per category. The arrays contain names of photos. The arrays
> look like this:
>
> $cat_1 = array('moonlight.jpg'', shadow.jpg', 'luna.jpg');
> $cat_2 = array(...);
> $cat_3 = array(...);
> $cat_4 = array(...);


A lot of people lately seem to be using this kind of construct. To put it
simple: _don't_ do that. The name of a variable should hold no important
data save for identification of the variable by both interpreter & coder..

The correct way to do this is:

$cats = array(
1 => array('moonlight.jpg' .......),
2 => array(....),
3 => array(....));

And then just use:

foreach($cats[$_GET['cat'] as $img) echo $img;

> $cat = $_GET['cat']; //output: 1
> $sel_array = 'cat_' . $cat;//create the string: cat_1


You could use ${'cat_'.$cat} (or $$sel_array). This would be an unwise
choice though.
--
Rik Wasmus
Reply With Quote