1

If this is a over discussed question, forgive me. I started my self-study php 10 days ago and I have to do one exercise. I 've read related articles through several sources also incl php manual. I don't have too much programming knowledge, so what I did is somehow not so good. Anyway I write here because I hope that somebody could explain me what mistake I made, how should it be done. So tks in advance. The exercise is :

Complete the below PHP script so that it prints the sum and average of given points. The points are sent to the script as a character string, where points are separated with comma (e.g. 4,5,2). Points are divided into an array with the explode-function. The purpose of the script is to print the points separated with a space. Write only the missing statements, don’t write the whole program in the text box. Incomplete program:

    $numberstring = $_GET['numberstring'];
    $numberarray = explode(',',$numberstring);

    // Your code here

    echo "Points were: $points\n";
    echo "Sum of points: $sum\n";
    echo "Average of points: $average";
 ?>

 Example output

 Points were: 3 6 7 -2 0
 Sum of points: 14
 Average of points: 2.8

And here in below is what I tried:

 <html>
 <head>
 <title>Online PHP Script Execution</title>
 </head>
 <body>

 <?php


       $numberstring = $_GET['numberstring'];
       $numberarray = explode(',',$numberstring);


          for ($i=0; $i<=$numberarray.length;$i++)

             echo "points were:" ;      

             { $points=$numberarray[$i];
                $sum=$points+$sum;

               echo $points; 

              };


             echo "Sum of points: $sum\n";

               while ($i!=0)

               {$average=$sum/$i;

                }

              echo "Average of points: $average";
    ?>
    </body>
    </html>
1

5 Answers 5

3

You have to use some functions :

To print points, you can use implode(' ', $numberarray) It will show points separated with a space. (See implode())


Sum can be get by function array_sum() : This function calculate the sum of values in an array.

$sum = array_sum($numberarray);

Finally, average can be get by this code :

$average = array_sum($numberarray) / count($numberarray); 

Result :

$points = implode(' ', $numberarray);
$sum = array_sum($numberarray);
$average = array_sum($numberarray) / count($numberarray); 

echo "Points were: $points\n";
echo "Sum of points: $sum\n";
echo "Average of points: $average";

About code you have done :

for ($i=0; $i<=$numberarray.length;$i++)

This will not work. In PHP, if you want to get number of elements in array, you have to use count()

for ( $i = 0 ; $i < count($numberarray) ; $i++ ) { ... }

Also, you write echo "points were:" ; between for() and {. You will get a Fatal Error. You have to move your echo before loop

echo "points were:" ; 
for ( $i = 0 ; $i < count($numberarray) ; $i++ ) {
    $points = $numberarray[$i];
    $sum = $points+$sum; // You can also do $sum += $points;
    echo $points." ";
}

About your while() loop, it will loop infinite and you don't need to do a loop. You can simply do :

$average = $sum / count($numberarray);

You final code will look like :

$numberstring = $_GET['numberstring'];
$numberarray = explode(',',$numberstring);

echo "Points were:" ; 
for ( $i = 0 ; $i < count($numberarray) ; $i++ ) {
    $sum += $numberarray[$i];
    echo $numberarray[$i]." ";
}
echo "\n";

$average = $sum / count($numberarray);

echo 'Sum of points: '.$sum."\n";
echo 'Average of points: '.$average;

EDIT with some validations/optimizations :

$numberstring = $_GET['numberstring'];
$numberarray = explode(',',$numberstring);
$cptElements = count($numberarray); // create a variable to not call count() multiple times.

if ( $cptElements )
{
    $numberarray = array_map ('intval', $numberarray); // convert all values to int.

    echo "Points were:" ; 
    for ( $i = 0 ; $i < $cptElements ; $i++ ) {
        $sum += $numberarray[$i];
        echo $numberarray[$i]." ";
    }
    echo "\n";

    echo 'Sum of points: '.$sum."\n";
    echo 'Average of points: '.($sum / $cptElements);
}
else
{
    echo 'No points';
}
Sign up to request clarification or add additional context in comments.

7 Comments

Hi! Tks for all of your answers. I don't have enough points to vote all of you up. But many tks!
@djidi Why to implode again when he is already getting a comma seperated strin in $_GET
@Veerendra : "The purpose of the script is to print the points separated with a space"
@lau : edited answer with help about errors in you original code
@djidi ok, I've just asked one question and it is deleted somehow. Anyway I was asking if the array counts happened to be zero, will I get an error when I try to divid $sum by 0 -->$average=$sum/count($numberarray)?
|
1

Shouldn't something like this do all you want:

$string = $_GET['numbers'];
$numbers = array_map('intval', explode(',', $string));

$sum = array_sum($numbers);

$average = $sum / count($numbers);

The array_map function can execute another function on all elements in the array (this one makes sure you are dealing with only integer values). Try using as much functions from PHP as possible; array_sum() and count(). The first one adds up all the elements in the array, and the second one counts the number of elements in the array. These two function combined can generate the average for you.

In your example-code, I can see for ($i=0; $i<=$numberarray.length;$i++) $numberarray.length looks like javascript to me... not PHP, try using the count() method mentioned earlier

4 Comments

Why to implode again when he is already getting a comma seperated strin in $_GET
@JaMaBing: indeed, i added clarifications
"The purpose of the script is to print the points separated with a space."
@Veerendra: what do you mean exactly?
1

Use this

$numberstring = $_GET['numberstring'];
$numberarray = explode(',',$numberstring);


echo "Points were: ".$numberstring;*/
echo "Sum of points: ".array_sum($numberarray );
echo "Average of points: ".array_sum($numberarray)/count($numberarray);

1 Comment

Why to implode again when he is already getting a comma seperated strin in $_GET
0

Here you go

<?php

        $numberstring = $_GET['numberstring'];
        $numberarray = explode(',',$numberstring);

        // Your code here
        $sum = array_sum($numberarray);
        $count_arr = count($numberarray);
        $average = $sum/$count_arr;
        $points = str_replace(',',' ', $numberstring);

        echo "Points were: $points\n";
        echo "Sum of points: $sum\n";
        echo "Average of points: $average";
     ?>

2 Comments

:-), straightforward answer:D, but i will go through all the answers today. tks!
I did:-) Have a nice day!
0

PHP does not have a length property on Arrays. Use count($array_here). Also, Object (class in PHP) properties are accessed with -> not ., and you're not using an Object. In your case you don't even need a loop. Your PHP should look more like:

<?php
function array_average($ary){
  return array_sum($ary)/count($ary);
}
if(isset($_GET['numberstring'])){
  $number_string = $_GET['numberstring'];
  $number_array = explode(',', $number_string);
  echo 'points were:'.$number_string.'<br />'.
  'sum of points:'.array_sum($number_array).'<br />'.
  'average:'.array_average($number_array);
}
?>

1 Comment

Tks!:-). Good to know that I used a wrong type of property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.