PHP printf question

dsarosh

Adept
Hello,

When I use this php code:

<?php

$sentence="This is a stentence whose words are to be counted.";

printf("The number of words in \"$sentence\" is: %d words.
", $sentence, str_word_count($sentence));

?>

I get the following output:

The number of words in "This is a stentence whose words are to be counted." is: 0 words.

When I use this php code:

<?php

$sentence="This is a stentence whose words are to be counted.";

printf("The number of words in \"$sentence\" is: %f words.
", $sentence, str_word_count($sentence));

?>

I get the following output:

The number of words in "This is a stentence whose words are to be counted." is: 0.000000 words.

When I use this php code:

<?php

$sentence="This is a stentence whose words are to be counted.";

printf("The number of words in \"$sentence\" is %s words.
", $sentence, str_word_count($sentence));

?>

I get the following output:

The number of words in "This is a stentence whose words are to be counted." is This is a stentence whose words are to be counted. words.

When I use this php code:

<?php

$sentence="This is a stentence whose words are to be counted.";

echo "The number of words in \"$sentence\" is ".str_word_count($sentence). " words.
";

?>

I get the following correct output:

The number of words in "This is a stentence whose words are to be counted." is 10 words.

I thought the printf function was more powerful than the echo command. Does anyone have any comment? Why is the printf() function not displaying the number of words? It either displays 0 or 0.0000 or the entire string again, but never the correct number. I tried type casting to (int) but still didn't work.
 
in your first printf you specified $sentence itself then %d, but passed params as first $sentence then the count function... so $sentence was getting passed to %d.... make your printf like this:

Code:
printf("blah blah yak yakety yak %s has %d words", $sentence, str_word_count($sentence));

side question: are you a programmer by profession? aim to be one?
 
You're right, I got it now. I was making a simple mistake.

I was passing two arguments, but I was passing only one placeholder... silly mistake.

The code should have been:

printf("The number of words in \" %s \" is: %d words.
", $sentence, $str_word_count($sentence));

I am mech engineer by education, but have spent quite some time with code in a casual manner. I'm getting some basics of php, javascript under my belt, it's quite interesting too.
 
Like all good programmers are...:)

At the risk of going off focus here... let me ask you:

What do you think of my choice of choosing html, css, javascript, php/mysql as the things to focus on, at least for the time being?

I know others are doing .net and mobile developing and java, Adobe AIR, etc, etc.

But I have chose the above ones. Any thoughts?
 
Back
Top