Jump to content

Oparations with Arrays


AnaTeixeira

Recommended Posts

Hi everyone, 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?

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/282971-oparations-with-arrays/
Share on other sites

You can't echo operations, You need to use if or else statements.

$operation = $_POST['SelectedOperation']

if($operation == 'count') {
    echo count($array);
} elseif ($operation == 'sum') {
    echo array_sum($array);
}

You can have as many elseif statements as you require.

I suppose this sounds like what you want to do?

 

<form action='' method='post'>
<input type='text' name='av[]' /><br/>
<input type='text' name='av[]' /><br/>
<input type='text' name='av[]' /><br/>
<input type='text' name='av[]' /><br/>
<input type='text' name='av[]' /><br/>
<input type='submit' name='operation' value='array_sum' />
<input type='submit' name='operation' value='count' />
<input type='submit' name='operation' value='end' />
</form>

<?php
if ($_POST) {
  $array = array_filter($_POST['av']); // filter out empty values
  $func = $_POST['operation'];
  if ( function_exists($func) )
    echo call_user_func($func,&$array);
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.