0

i need some help.

I have an array ($array) - Array ( [0] => 1374410400 [1] => 1374394500 [2] => 1374384000 [3] => 1374304800 [4] => 1374291900 ).

And the operation that will be used in array is defined by the user. The operation could be array_sum, count and end.

I want to "merge" this two (array + operation), like this $operation.'('.$array.')'.

When I echo this $operation.'('.$array.')'. only appears count(Array).

But when i write "count($res)" appears the result.

Anyone knows the answer?

Sumit Bijvani
  • 8,154
  • 17
  • 50
  • 82

4 Answers4

0

Looks like you need "variable variables" See documentation

Joao
  • 2,696
  • 2
  • 25
  • 35
0
echo $operation.'('.$array.')';

will echo a string formed from string $operation + string ( + string $array + string ).

If you want to execute the operation whose name is stored in $operation, the simplest syntax is:

echo $operation($array);

Note: you almost certainly want to do some validation of the user's input, else you'll get a fatal error if they use an undefined function and so on.

Arkaaito
  • 7,347
  • 3
  • 39
  • 56
0

Yes it will only print the string, use the function to get the desired result. function FunctionName($operation, $array){ if($operation =='count'){ return count($array); } }

Abbasi
  • 617
  • 7
  • 14
0

See the documentation for call_user_func().

$results = call_user_func($operation, $array);

Make sure you don't allow the value of the $operation variable to be set directly by the user. Otherwise a malicious user could execute unwanted code on your server. Use the user input to determine which of the operations to run.

emarref
  • 1,286
  • 9
  • 18