Using an associative array as php function's input in PHP Server Side Scripting Language?

editAnswer

reportReport

Answer(s) available: 1

Shrinath Sachar

, Electric Meter Installer, Database Customer Experience Strategy Phone Calls

"
"

why not write all functions this way?

"
"

For that matter, why not forget about parameters completely, and use global variables for everything? (kidding)

"

Passing an associative array has one useful advantage: you can make multiple function parameters optional, and you can pass a value for the Nth parameter without having to pass a value for the *N-1*th parameter.

"

But you have no way to make mandatory parameters with a compile-time error if you don't pass them. Neither can you declare type-checking.

"

You'll have to write code inside the called function to check for the presence and the type of required parameters.

"

An alternative I have used is to declare conventional parameters for those that are mandatory, and then as the last (optional) argument, declare an associative array called $options that contains only the optional items.

"
function database_connect($dbname, $user, $password, array $options = array())"
"

thumb_upUpvote18

smsComment

reportReport