0

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?

2
  • 5
    Provided example is completely valid. Why can't you just test it by yourself and get the answer yourself? :) Commented Nov 15, 2009 at 17:37
  • Well, if for no other reason, now there is a searchable record of it on the web. So someone who went looking like I did will find it. Commented Nov 15, 2009 at 17:41

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@Alcon: You’re right. The lack of a clear language grammar is sometimes really bugging.
3

both keys and values can be arbitrary expressions*

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

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.