views:

98

answers:

3

I'm sure this has been asked before but I can't find it. The PHP documentation unclear on this and I can't find any examples like this. Is it legal to use variables in the declaration of an array use the array() construct? Not as keys, as the values. Like this:

function myFunc($value1, $value2, $value3) {
    $myArr = array('value1' => $value1, 'value2' => $value2, 'value3' => $value3);
    return $myArr;
}

Is that legal?

+4  A: 

Yes, that is legal. Otherwise you would get an error.

Gumbo
I'm not to the point of running it yet, and won't be for a little while. I wanted to make sure this was legal before I wrote a whole bunch more code based on it. I just couldn't find an example of it used on the web or in the PHP documentation. And the documentation was a little vague on the issue.
Daniel Bingham
@Alcon: You’re right. The lack of a clear language grammar is sometimes really bugging.
Gumbo
+3  A: 

both keys and values can be arbitrary expressions*

 $r = array(
     phpversion() => 1 + 2 - 3,
 );
  • except that keys cannot be arrays/objects/resources
stereofrog
+1  A: 

Yes, it's absolutely legal! You can also use variables for the key names:

$myArr = array($thekey => $theval);

The key or value for any key/value pair doesn't need to be in any particular format, it just needs to evaluate out to a primitive type (i.e.: a number or string). The array() construct simply looks for the "simplified" values that it's passed; it doesn't care what they are or how they got there.

Hope this helps!

mattbasta