English 中文(简体)
Declaring an Array using Variables and the array() construct in PHP
原标题:

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?

最佳回答

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

问题回答

both keys and values can be arbitrary expressions*

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

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!





相关问题
Benefits of declaring a function as "inline"?

Every time I read about the "inline" declaration in C it is mentioned that it is only a hint to the compiler (i.e. it does not have to obey it). Is there any benefit to adding it then, or should I ...

热门标签