16

I have an array of colors having dynamic values which depends on database. now these values are required in a function which takes values only like this function('para1','para2','para3','para4') where param1 to param4 are color values in an array. Problem is how can i parse these values to that function in the above stated format.Only a programminng logic required.Language is php.

Suppose dynamic array is color[]=('red','maroon','blue','green'); and these value should be passed to this function like :setLineColor('red','maroon','blue','green');

I m using this function for creating graphs.(Lib using PHP_graphlib: link: http://www.ebrueggeman.com/phpgraphlib/documentation.php) Any other suggested library is welcomed.Plz provide a simple example with it.

Aakash Sahai
  • 3,935
  • 7
  • 27
  • 41

3 Answers3

37

Since PHP 5.6 you can use argument unpacking with the triple-dot-operator:

setLineColor(...$colors);
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
  • 2
    Very nice, much easier on the eyes as `call_user_func_array` and also practical, if you want to combine "fixed" args with arrays like `fprintf(STDOUT, $format,...$args)` – DBX12 Aug 10 '18 at 18:09
22

You can use the function call_user_func_array.

<?php
$colors = array('red','maroon','blue','green');
call_user_func_array('setLineColor', $colors);
?>

If you want to call the method of an object, you can use this instead:

<?php
$graph = new ...
$colors = array('red','maroon','blue','green');
call_user_func_array(array($graph, 'setLineColor'), $colors);
?>
Hannele
  • 9,301
  • 6
  • 48
  • 68
Enrico Stahn
  • 2,967
  • 1
  • 23
  • 23
-5
function($color[0], $color[1], $color[2], $color[3])
animuson
  • 53,861
  • 28
  • 137
  • 147
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99