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

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
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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

Post 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? :?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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);
 
}
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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

Post by Luke »

Perfect! Thanks :)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

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

Post by Weirdan »

call_user_func_array is an overkill. vsprintf() does just that.
Post Reply