Page 1 of 1

sprintf - how do i use an array as replacement values?

Posted: Tue Jan 26, 2010 1:03 am
by Luke
I'm trying to build a really simple db class for this lame project I'm working on. I want to build an "buildQuery" method that basically just applies sprintf to a query. For instance:

Code: Select all

$db->buildQuery("UPDATE `users` SET `active` = %d WHERE `activation_code` = '%s'", array(1, 'a88jek3kl'));
The method would work something like this:

Code: Select all

// ..snip
 
public function buildQuery($query, $values) {
 
   return sprintf($query, $values);
 
}
 
// ..snip
The problem is that this doesn't do what I intend it to do. sprintf expects a variable length list of arguments rather than an array. I need to use an array, so how do I go about this? Am I missing something obvious? :?

Re: sprintf - how do i use an array as replacement values?

Posted: Tue Jan 26, 2010 1:49 am
by requinix
No, it's not obvious. But there is a function to do this kind of stuff: call_user_func_array (don't let the "user" confuse you).

Code: Select all

public function buildQuery($query, $values) {
 
   $arguments = $values;
   array_unshift($arguments, $query);
   return call_user_func_array("sprintf", $arguments);
 
}

Re: sprintf - how do i use an array as replacement values?

Posted: Tue Jan 26, 2010 2:03 am
by Luke
Perfect! Thanks :)

Re: sprintf - how do i use an array as replacement values?

Posted: Tue Jan 26, 2010 4:28 am
by Weirdan
call_user_func_array is an overkill. vsprintf() does just that.