3

I have a php (v. 7.0.16) script running on the command line with this:

$ct = 1;
foreach($sort_this as $cur_site_id => $dx){

    $cur_location = $locations[$cur_site_id]['location'];
    $msg = "\033[A\33[2K\r" . 'getting data for %25s (' . $cur_site_id . ') store: %7s %01.2f' . "\n";
    echo printf($msg, $cur_location, ($ct . ' / ' . count($sort_this)), number_format((($ct / count($sort_this)) * 100), 2));
    $ct++;
}

This loop runs about 40 iterations. The printf statement works with 1 small problem. On the line after the "getting data" line I see a number that increments from 7x-7y as it runs (sometimes it starts at 71, sometimes at 77, etc.). I can't figure out what's causing this number to be printed. So when the loop starts I see something like this on the screen:

getting data for                  DENVER (531) store: 42 / 42 0.00
77

and when it finishes something like this:

getting data for                 SEATTLE (784) store: 42 / 42 100.00
79

I found how to print to the same line and clear the data here:

Erase the current printed console line

Is there a way to prevent the 7x codes from showing? Also, what are they?

Community
  • 1
  • 1
raphael75
  • 2,982
  • 4
  • 29
  • 44

2 Answers2

8

The problem is on this line:

echo printf(...)

printf() generates a string using its arguments (format and values) and prints it. It returns the number of printed characters (the length of the string it generated).

Your code then passes this value to echo that prints it. This is the source of the extra number in the range of 70-77.

You should either remove the echo or use sprintf() instead of printf().

sprintf() generates the string the same was printf() does but it doesn't print it; it returns it and it is passed as argument to echo that displays it.

axiac
  • 68,258
  • 9
  • 99
  • 134
1

printf() returns the length of the outputted string.

See PHP docs:

Return Values: Returns the length of the outputted string.

Just remove echo fom that line.

Shira
  • 6,392
  • 2
  • 25
  • 27