Array values as function parameters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Array values as function parameters

Post by Maugrim_The_Reaper »

Couldn't see how it was possible (maybe it's not!).

Say I have an array of values, where the count is not fixed - i.e. cannot use the number index for this one. I have a PHP function, like say mysqli_stmt_bind_param() which accepts an arbitrary number of variables to bind to a prepared statement. Is it possible to inject the array values into such a function through some wizardry or am I completely lost and need to fall back on a foreach loop?

Some example of what I mean. In attempting to hack an ExecuteStatement method for an abstraction class, I start building:

Code: Select all

function ExecuteStatement($statement, $inputarr) {
		if($inputarr)
		{
			// Better to bind them before now!
			$this->BindParameters($statement, $inputarr);
		}
		$resultID = mysqli_stmt_execute($statement);
	}

	function BindParameters($stmt, $inputarr) {
		$type = '';
		$params = array();
		foreach($inputarr as $param) {
			switch(gettype($param)){
				case 'string':
					$type .= 's';
					break;
				case 'integer':
					$type .= 'i';
					break;
				case 'double':
					$type .= 'd';
					break;
				case 'boolean':
					$param = $param ? 1 : 0;
					$type .= 'i';
					break;
				default:
					if ($param === null) {
						$param = 'NULL'; // how does one specify NULL for binding?
					}
					$type .= 's'; // binds an empty string rather than a NULL value (temp)
			}
			$params[] = $param;
		}
		mysqli_stmt_bind_param($stmt, $type, $params); // bad syntax I know...
	}
End result in theory (I know about the last syntax error - it's intentional) is to get $params into the function. mysql_stmt_bind_param() syntax is actually:

bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

call_user_func_array() should work just fine for this.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

I'm seriously thinking about memorising the manual...;)

Thanks!
Post Reply