note 82647 deleted from function.sprintf by felipe
| From: | felipe@php.net | Date: | Sun, 20 Apr 2008 11:39:05 +0000 |
| Subject: | note 82647 deleted from function.sprintf by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-138563@lists.php.net to get a copy of this message | ||
Note Submitter: karl dot rixon at gmail dot com
Reason: 1
----
This function is basically an alternative for sprintf that allows you to pass individual arguments
as normal, but also allows you to pass an array of replacements as the second argument instead of
listing them individually.
<?php
function sprintf_array()
{
$args = func_get_args();
// if replacements were passed as an array instead of individual
// arguments, append them to the main array
if (is_array($args[1]))
{
$replace = $args[1];
for ($i=1; $i<=sizeof($replace); $i++)
{
$args[$i] = $replace[$i-1];
}
}
// if one argument was passed, return that argument
// (could also return false if preferred)
if (sizeof($args) < 2)
{
return $args[0];
}
else
{
$replaced = @call_user_func_array('sprintf', $args);
if ($replaced !== false)
{
return $replaced;
}
}
// return an empty string on failure (or false if preferred)
return "";
}
?>
Examples:
<?php
$num = 10;
$location = "tree";
$array_args = array(10,"tree");
$format = 'There are %d monkeys in the %s';
echo sprintf_array($format, $num, $location);
echo sprintf_array($format, $array_args);
// both examples will output:
// There are 10 monkeys in the tree
?>
Hope that helps someone.