The median is the middle value of the given list of data when it is arranged in order. This list can have an even number of elements or an odd number of elements.
In this shot, we will discuss the steps to find the median.
First, we have to sort the array we are going to use. We can use PHP’s built-in sort()
method.
For example, let’s sort an array that contains 6, 11, 4, 21, 12
.
<?php// Create an array$numbers = [6, 11, 4, 21, 12];// Sort the arraysort($numbers);// Print the sorted arrayprint_r($numbers);?>
It’s very straightforward to get the middle element in an array that contains an odd number of elements.
You can use the following method to retrieve the index of the middle element:
Now that you have the index of the middle number, the median is the number at that index.
See the code below to get the median of a sorted array that contains an odd number of elements.
<?php// Create sorted array$numbers = [4, 6, 11, 12, 21];// Get array length$length = count($numbers);// Divide length by 2$half_length = $length / 2;// Convert to integer$median_index = (int) $half_length;// Get median number$median = $numbers[$median_index];// Output medianecho $median; // Should be 11?>
In an array with an even number of elements, the process is a bit different, as there’s no middle element. Instead, we have to find the average of the two middle elements.
To get the indices of these two middle elements:
Now, get the values at these indices and find their average; this value is the median of the array.
Take a look at the code below to find the median of a sorted array that contains an even number of elements.
<?php// Create sorted array$numbers = [4, 6, 11, 12, 18, 21];// Get array length$length = count($numbers);// Divide length by 2$second_half_length = $length / 2;// Subtract 1 from $second_half_length$first_half_length = $second_half_length - 1;// Get index values$first_half = $numbers[$first_half_length];$second_half = $numbers[$second_half_length];// Get average of these values$median = ($first_half + $second_half) / 2;// Output medianecho $median;?>