Why is the return 115?

Asked

Viewed 35 times

0

The question is quite explanatory. Because the return in the last %s is 115?

$key = 0;
$count = 33;
$id = 1;
echo printf("%s de %s - ID: %s", ++$key, $count, $id);
// 1 de 33 - ID: 115

2 answers

2


Because the return of printf is the amount of characters written, you can check this in documentation.

The problem with your code is that it does two prints: that of the printf and that of echo. You probably just wanted to do the printf.

$key = 0;
$count = 33;
$id = 1;
printf("%s de %s - ID: %s", ++$key, $count, $id);

0

The printf already prints an output on the screen, right after the echo writes the return of printf, which is the size of the printed string.

Use without the echo which will have the expected result:

$key = 0;
$count = 33;
$id = 1;

printf("%s de %s - ID: %s", ++$key, $count, $id);
// 1 de 33 - ID: 1

Behold working.

Or use the sprintf to return the value and display with echo instead of printing it directly:

<?php

$key = 0;
$count = 33;
$id = 1;

echo sprintf("%s de %s - ID: %s", ++$key, $count, $id);

Behold working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.