-1

I am trying to modify phpgraphlib so that I can generate a legend when multiple bar colors are used. I added an array with colors as optional parameter in generateLegend() but it doesn't seem to work. I don't know what's wrong. I have no prior experience with PHP, but it seemed to me passing an array as optional parameter must be possible Here is my code:

protected function generateLegend(array $colors = array())
{
    // here is some code        
    if($this->bool_multi_color_bars) {
        // gets here
        if (!empty($colors)) {
            // doesn't get here
            $index = 0;
            foreach($colors as $key => $item) {
                // here is some code that creates the colored boxes
                $index++;
            }
        }
    }
}

And here is the code that calls the function:

$colors = array();
foreach($data as $key => $value) {
    if($value < 3) {
        $colors[$key] = 'green';
    }
    elseif($value < 8) {
        $colors[$key] = 'orange';
    }
    else {
        $colors[$key] = 'red';
    }
}
$graph->setBarColors($colors);
$graph->setLegend(true, $colors);
$graph->createGraph();

EDIT: generateLegend() is called with the follwing code:

if ($this->bool_legend) { 
    $this->generateLegend(); 
}

For the sake of readability I left most of the code out, but I can see that the method is called (therefore I added the comments where the code does get and not)

Caconde
  • 4,177
  • 7
  • 35
  • 32
no-name
  • 477
  • 1
  • 5
  • 13
  • 3
    There's no call to `generateLegend` in your posted code – Philipp Feb 28 '18 at 10:40
  • Thanks for your comment. There is actually, but I left most of the code out for readability. Your comment helped me actually, I see that I need to pass the parameter with another function maybe – no-name Feb 28 '18 at 10:48
  • So you don't pass an argument to `generateLegend()`? Then `empty($colors)` will be `true`. – Karsten Koop Feb 28 '18 at 10:56

1 Answers1

0

I'm not sure, what you actually want. What you currently see is the expected behavior of empty. An array without elements is empty.

var_dump(empty([])); // true

If you want to test, if the optional param was actually set, you could use func_num_args.

if (func_num_args() > 0) {
    // $colors was set
}

Or use an other default argument and test against the type.

function foo(array $bar = null) {
    if ($bar === null) {
        // ...
    }
}
Philipp
  • 15,377
  • 4
  • 35
  • 52