Ash_ADA
Ash_ADA

Reputation: 3

Why does this printf output 27 repeatedly?

<?php

$letters = range(A,Z);

$format_string = '<li><a href="#%s">%s</a></li>';

foreach ($letters as $key => $letter) {
    echo printf($format_string,$letter, $letter);
}

?>

This is meant to print out an li with the alphabet from A-W, however the output looks like this:

etc.. all the way up to the last number.

Using a regular echo with string concatenation outputs the list fine without any 27's.

Upvotes: 0

Views: 40

Answers (1)

iainn
iainn

Reputation: 17434

You're calling echo with the return value of the call to printf, which is defined in the manual as

Returns the length of the outputted string.

So your printf call is running, and displaying your string. This is returning 27, which is the length of the string <li><a href="#%s">%s</a></li> once a single letter has been inserted into it. The call to echo is then displaying that after the string itself has been shown.

In short, either remove echo or as mentioned in a comment, use sprintf instead, which returns the string instead of displaying it.

Upvotes: 1

Related Questions