Home > Article > Backend Development > How to define an array and find the average in PHP
PHP is a widely used and very popular open source programming language. In PHP, array is a very important data type used to store multiple values. This article will show you how to define an array and find its average.
Define Array
Defining an array in PHP is very simple. Here is a basic example:
<?php $number_array = array(2, 4, 6, 8, 10); ?>
The above code creates an array named $number_array
, which contains 5 elements: 2, 4, 6, 8, and 10.
Copy the above code into your local PHP environment, save it as a .php file and open it in the browser, you will see that there is no output on the page. This is because we haven't told PHP how to print this array. Here is a simple example:
<?php $number_array = array(2, 4, 6, 8, 10); print_r($number_array); ?>
In the above code, we have used the PHP built-in function print_r
to print the array. After running the above code, we will see the following output:
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
The output here tells us that this array consists of 5 elements and each element has a unique index. In PHP, the index of an array can be a number or a string.
Find the average
Now that we have an array containing numbers, we can use a loop structure to iterate through it and calculate the average of these numbers. Here is a simple example:
<?php $number_array = array(2, 4, 6, 8, 10); $sum = 0; $count = count($number_array); for($i = 0; $i < $count; $i++) { $sum += $number_array[$i]; } $average = $sum / $count; echo "平均数是:" . $average; ?>
In the above code, we have used a loop to iterate through the array and add each number. We use the variable $sum
to store the sum of all numbers and the PHP built-in function count
to get the number of elements in the array. Once we have calculated the sum, we can calculate the average and then output it using the echo
statement.
After running the above code, we will see the following output:
平均数是:6
This tells us that the average of these numbers in the array is 6.
Conclusion
In this article, we have introduced how to define an array and calculate its average using PHP. Although this example is very simple, it can serve as the basis for more complex PHP applications. In real projects, arrays and loop structures are common tools in PHP programming, so it is very important to know how to operate on them.
The above is the detailed content of How to define an array and find the average in PHP. For more information, please follow other related articles on the PHP Chinese website!