note 82647 added to function.sprintf

From: Date: Sun, 20 Apr 2008 09:36:32 +0000
Subject: note 82647 added to function.sprintf
Groups: php.notes 
Request: Send a blank email to php-notes+get-138561@lists.php.net to get a copy of this message
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. ---- Server IP: 92.48.100.16 Probable Submitter: 87.194.133.227 ---- Manual Page -- http://www.php.net/manual/en/function.sprintf.php Edit -- https://master.php.net/note/edit/82647 Del: integrated -- https://master.php.net/note/delete/82647/integrated Del: useless -- https://master.php.net/note/delete/82647/useless Del: bad code -- https://master.php.net/note/delete/82647/bad+code Del: spam -- https://master.php.net/note/delete/82647/spam Del: non-english -- https://master.php.net/note/delete/82647/non-english Del: in docs -- https://master.php.net/note/delete/82647/in+docs Del: other reasons-- https://master.php.net/note/delete/82647 Reject -- https://master.php.net/note/reject/82647 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138561) next »