Forum Moderators: coopster

Message Too Old, No Replies

dynamic variable names

How are they created?

         

brucebertrand

11:10 pm on Mar 12, 2005 (gmt 0)

10+ Year Member



Ok, I've got something like this:

if ( $host[$i][detail1stuff]!= "" ){
some_code_here;
}

if ( $host[$i][detail2stuff]!= "" ){
some_code_here;
}

etc...

I want to do something like this:

for ($count = 1; $count <= 100; $count++ ){
if ( $host[$i][details{$count}stuff]!= "" ){
some_code_here;
}
}

However, the above doesn't work.
Does anyone know how to do this?

Thanks.

coopster

11:17 pm on Mar 12, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, brucebertrand.

If you use double-quotation marks, PHP will parse that variable for you.

if ( $host[$i]["details{$count}stuff"]!= "" ){

brucebertrand

11:52 pm on Mar 12, 2005 (gmt 0)

10+ Year Member



Thanks for the quick response.

I also remembered about string concatenation operator.

So:

if ( $host[$i][details.$count.stuff]!= "" )

also works.

coopster

2:30 am on Mar 13, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



That's true, but without any quotation marks around the array index PHP is going to complain about an undefined index. Well, it will if you have your error_reporting() [php.net] on during development (which is a good idea, by the way).

Notice: Use of undefined constant details - assumed 'details' in ...