This, again, is a very simple code.
This is my 2nd polyglot question and this time I've tried to do something that I miss sometimes in Javascript.
PHP has the array_sum()
function, but Javascript has no direct equivalent.
So, I decided to make one that works with both languages!
Here is the code:
function sum_array()
{
if( $javascript = '\0' == "\0" )
{
$vars = new Object();
$vars['args'] = arguments;
$vars['l'] = arguments.length;
}
else
{
$vars = Array();
$vars['args'] = func_get_args();
$vars['l'] = func_num_args();
}
for( $vars['sum'] = $vars['i'] = 0; $vars['i'] < $vars['l']; $vars['i']++ )
{
$vars['m'] = $javascript ? $vars['args'][$vars['i']].length : count($vars['args'][$vars['i']]);
for( $vars['j'] = 0; $vars['j'] < $vars['m']; $vars['j']++ )
{
$vars['sum'] += ( $vars['args'][$vars['i']][$vars['j']] / 1 ? $vars['args'][$vars['i']][$vars['j']] : 0 );
}
}
return $vars['sum'];
}
Usability is really easy:
Simply pass multiple array
s as arguments. In PHP, it is required to be an array
with only numeric keys. This is due to the limitations of Javascript.
Example of usage:
sum_array([1,2,3,4,5],[15]); //should return 30 in Javascript and PHP 5.4+
To avoid 'poisoning' the window
object, I only created 2 variables and use one of them as an array
(The other is just to save if we are running in Javascript or PHP).
Was this a good decision?
What else can I improve on my code?