0

I'm trying to figure out how if the user input like : avg(2,3,6,1) 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.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Rakhadin
  • 33
  • 6
  • 2
    Thew things: 1) In your if statement you have a simple assignment where you probably want a comparison (See: http://stackoverflow.com/q/2063480). 2) What you got inside `$i` is probably just going to be a string and just because you wrap it inside an array probably won't create the array you want it to. It will just create an array with one element and that is the string: `Array([0]=> "avg(2,3,6,1)")` (See: http://php.net/manual/en/language.types.array.php). – Rizier123 Oct 29 '16 at 02:57
  • Also if your string is really `avg(2,3,6,1)` then you probably want to look at a simple regex to extract the numbers out of the string. – Rizier123 Oct 29 '16 at 03:04
  • Thank you so much much much for your explanation dude, now I got it (y) – Rakhadin Oct 29 '16 at 05:20

1 Answers1

0

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);
print_r($i);
$avg = array_sum($i) / count($i);
echo "<div class='msg'>Server : </div>";
echo $avg;
Jees K Denny
  • 531
  • 5
  • 27
  • poor me, know about explode things but confuse in 'when' to use it lol. Thank you so many much man u save my day :D – Rakhadin Oct 29 '16 at 05:21