Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do i get: Warning: printf() Too few arguments in php

Tags:

php

I get the error

Warning: printf() [function.printf]: Too few arguments 

Looking at the code I see:

function twentyten_posted_on() {
    printf( 
        sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><span class="entry-date">%3$s</span></a>',
            get_permalink(),
            esc_attr( get_the_time() ),
            get_the_date()
        )
    );
}

What seems to be the problem?

like image 613
Himmators Avatar asked Jun 18 '12 11:06

Himmators


People also ask

How many arguments can be passed to printf?

Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )

Does printf work in PHP?

Definition and Usage. The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step".


1 Answers

The printf() and sprintf() functions are identical; the only difference in their behaviour is that one is a statement (it does something) and the other is a function expression (it evaluates to something). (See this StackOverflow answer for a description of the difference.) They both take a format as the first argument, then zero or more additional arguments as replacement strings for special characters within the format string.

Your sprintf() function is well formed. You've numbered your format strings, you have replacement strings as arguments to match the format strings. All is good.

But consider what the printf() function is doing. It gets a string, which happens to be the output of sprintf(). If sprintf()'s contains a % character, then printf() would need a replacement string which is not included in your code.

As others have said, you can probably leave out the sprintf() from your code. But you should also understand WHY this is happening.

For example:

$fmt = "%%d\n";
printf( $fmt );
printf( sprintf($fmt) );
printf( sprintf($fmt), "Hello world" );

The first printf works, and prints a "%d". The second printf fails because its format string implies that it should have a replacement string, but none is provided. The third one prints a zero, because when you try to evaluate "Hello world" as a decimal integer (%d), that's what you get.

Look at your variables, and you'll probably find that at least one of them has a % character in it.

like image 115
ghoti Avatar answered Oct 31 '22 18:10

ghoti