Skip to content

PrintfScanfArguments ​

error on by default

Group: Probable bugs · PhpStorm name: PrintfScanfArgumentsInspection

The printf/scanf family takes as many value arguments as the format string has conversions. A missing or extra argument silently produces wrong output (or an ArgumentCountError in PHP 8), and a stray % makes the format invalid.

Example ​

php
<?php
class Report
{
    const ROW = '%s: %d%%';
    public static $line = '%-10s|%5.1f';
    private $head = '%%title%% %s';

    public function render($fh, $name, $total, $raw)
    {
        $fmt = '%%%s=%x';
        echo sprintf($fmt, $name);
        fprintf($fh, self::ROW, $name, $total, $raw);
        echo sprintf(self::$line, $name);
        echo sprintf($this->head);
        echo sprintf('50 %, total %s', $name);
        sscanf($raw, '%d-%d', $a);

        echo sprintf('%05.2f %s', $total, $name);
        echo sprintf("%2\$'#8s %1\$s", $name, $total);
        echo sprintf('%2$s %1$s', $name);
        [$x, $y] = sscanf($raw, '%d-%d');
        $parts = fscanf($fh, '%s %s');
        store(sscanf($raw, '%s'));
        sscanf($raw, '%*d %s', $only);
        sscanf($raw, '%[a-z]', $word);
        printf('%s %s', ...$pair);
        echo sprintf($unknown, $name);
        echo sprintf("Hi $name %s");
    }

    public function grow()
    {
        $tpl = 'id=%d';
        $tpl .= ' name=%s';
        return sprintf($tpl, 1, 'x');
    }
}

Reported:

  • line 11: This call needs 3 argument(s) in total.
  • line 12: This call needs 4 argument(s) in total.
  • line 13: This call needs 3 argument(s) in total.
  • line 14: This call needs 2 argument(s) in total.
  • line 15: Malformed format string.
  • line 16: This call needs 4 argument(s) in total.
  • line 20: This call needs 3 argument(s) in total.

Configure ​

In custos.json:

json
{
  "rules": {
    "PrintfScanfArguments": {
      "enabled": false
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore PrintfScanfArguments

/**
 * @noinspection PrintfScanfArgumentsInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.