Skip to content

array_shift causes arguments following a zero argument to be omitted #10

@robincafolla

Description

@robincafolla

Problem

Use of the return result from array_shift as the condition of the loop here:

while ($arg = array_shift($argv)) {

Causes any arguments after a zero argument to be omitted. This is because the zero value is evaluated as false.

Test case

//test.php
$cliConfig = [
  'a' => [
    'help' => 'A',
  ],
  'b' => [
    'help' => 'B'
  ],
  'c' => [
    'help' => 'C'
  ],
];

$cliArgs = new CliArgs($cliConfig);
var_dump($cliArgs->getArguments());

Running the above script with php test.php --a 1 --b 0 --c 1 will result in the following output:

array(3) {
  [0] =>  string(13) "/tmp/test.php"
  'a' =>  string(1) "1"
  'b' =>  NULL
}

The value for b is incorrect, and c is missing entirely.

Recommendation

Replace

while ($arg = array_shift($argv)) {

with

while (count($argv) > 0) {
  $arg = array_shift($argv);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions