6

In my web page, if a user choses certain options in a form, say

1. A -  Chosen
2. B -  Chosen
3. C -  Not Chosen

Then, sprintf() function in my script should accept that number of arguments -

sprintf("%s %s", valueOf(A), valueOf(B));

If all three are chosen, then

sprintf("%s %s %s", valueOf(A), valueOf(B), valueOf(C));

How can I achieve this?

1
  • I am wondering if you meant checkboxes instead of options? Commented Mar 29, 2012 at 11:30

4 Answers 4

13

What you want is probably the vsprintf function. It takes an array as the set of arguments. So in your case, you'd have something like this:

$args = <array_of_chosen_options>;
$fmt = trim(str_repeat("%s ", count($args)));
$result = vsprintf($fmt, $args);
Sign up to request clarification or add additional context in comments.

3 Comments

Why bother? Why not just implode(' ', <array_of_chosen_options>)?
@DaveRandom Of course, in the simple scenario in the question, implode would be a better solution, however in a more complex case, the formatting may be different for each selected element. vsprintf is a lot more flexible.
Thanks, nice and elegant solution!
3
  1. Generate the string of %s %s... dynamically
  2. Use vsprintf instead of sprintf
# // FOR DEMONSTRATION \\
$_POST["A"] = "subscribe_to_this";
$_POST["B"] = "subscribe_to_that";
# \\ FOR DEMONSTRATION //

$chosen = array();
if (isset($_POST["A"])) $chosen[] = $_POST["A"];
if (isset($_POST["B"])) $chosen[] = $_POST["B"];
if (isset($_POST["C"])) $chosen[] = $_POST["C"];

$format = implode(" ", array_fill(0, count($chosen), "%s"));
echo vsprintf($format, $chosen);

2 Comments

Why bother? Why not just implode(' ', <array_of_chosen_options>)?
@DaveRandom: Well, for my case, sprintf() is more cleaner. Actaully, It is a SQL query placeholder which I have. ("INSERT into ABC ('%s','%s'...)").
0

sprintf() is not really the way to do this. It is intended for static strings with dynamic place holders, not dynamic strings with an unknown number of place holders.

All your chosen options, no matter how you collected them, will probably end up in an array. So you could just implode() it, like this:

$arr = array(
  'Chosen option',
  'Another option'
  // ...
);

$str = implode(' ', $arr);

Yes, you could vsprintf() it, but why bother with the extra overhead of producing a format string which must be parsed and interpolated?

Comments

0

sprintf wouldn't be the ideal approach. Assuming that your HTML looks like

<input type="checkbox" name="options[]" value="A" /> A
<input type="checkbox" name="options[]" value="B" /> B
...

You can just do

$s = implode(" ", $_POST['options']);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.