Rhadin Rhadin - 1 year ago 92
PHP Question

Get input avg(example:2,4,3) to find the average

I'm trying to figure out how if the user input like :
and then the server will respond with the answer which is : Average of (2,3,6,1) is 3.
Here is my simple work and got stuck about the next implementation :( :

if($r['$msg']="avg(".$i")"){ //if message is avg(2,3,6,1)
$i = array($i);
$avg = array_sum($i) / count($i);
echo "<div class='msg'>Server : $avg</div>";

How to make it works? Sorry for the 'noob' code tho:(
Thank youu

Answer Source

You can do it with explode function in php. Convert the String to array. Check the below code, it will helps.

In your code $i = array($i); will output like Array ( [0] => 2,3,6,1 )

instead of creating 1-D array, you are creating 2-D array.

$i = "2,3,6,1";
//$r['$msg'] = "avg(".$i.")";
$i= explode(",",$i);
//$i = array($i);
$avg = array_sum($i) / count($i);
echo "<div class='msg'>Server : </div>";
echo $avg;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download