Take the 2-minute tour ×

I'm trying to use dynamic variable names (I'm not sure what they're actually called) But pretty much like this:

    $("file" . $i) = file($filelist[$i]);


The return is null which tells me it's not working. I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research. $filelist is defined earlier on.

share|improve this question
Don't! There is never a good reason to use them. They are, effectively, just an untidy array. Use a proper array instead. –  Quentin Feb 13 '12 at 8:37
Alright I'm sorry, I just went back and picked an answer for each question I've asked so far. Good thing it's only 7 :P –  user1159454 Feb 13 '12 at 8:56
And Quentin, why are they bad practice?? There must be a reason they exist alongside arrays I'd think –  user1159454 Feb 13 '12 at 8:57
@user1159454 — They are a disorganised mess without all the tools that can be applied to arrays available to them. They exist for ancient legacy reasons and crazy edge cases. –  Quentin Feb 13 '12 at 11:20
Crazy edge cases may be exactly why someone would want to ask this question. –  Vincent Nov 6 at 19:50

4 Answers 4

up vote 125 down vote accepted

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working Example

Using ${} is a way to create dynamic variables, simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there
share|improve this answer
Is it also possible to create dynamic arrays with the same logic? –  dtakis Sep 16 '13 at 13:20
I have the same doubt of @dtakis, can you help us? If possible, please take a look at this question. –  Marcio Simao Jul 6 at 0:54

Try using {} instead of ():

share|improve this answer

Tom if you have existing array you can convert that array to object and use it like this:

$r = (object) $MyQueryResult;
echo $r->key;
share|improve this answer

I do this quite often on results returned from a query..


// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

share|improve this answer
Have you ever tried to use extract() function of PHP? php.net/manual/en/function.extract.php –  DarkSide Oct 10 '13 at 12:12

Your Answer


