Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to expand an array elements as separate parameters to a function

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.

like image 983
Aakash Sahai Avatar asked Feb 17 '11 09:02

Aakash Sahai


People also ask

How do you pass an array as a parameter in a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can we pass whole array element from the function?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().

Can an entire array be passed as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.


Video Answer


2 Answers

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

setLineColor(...$colors);
like image 154
Fabian Schmengler Avatar answered Oct 06 '22 20:10

Fabian Schmengler


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);
?>
like image 23
Enrico Stahn Avatar answered Oct 06 '22 19:10

Enrico Stahn