Get the middle index of a PHP array.

This is a tutorial on how to get the middle index of a PHP array. In this guide, I will show you how to do this for both numeric arrays and associative arrays.

How to get the middle element of a numeric array.

In a numeric array, each array index is represented by a number. It is also typically ordered in an ascending order. As a result, it is actually pretty easy to calculate the index of the middle element:

In the PHP code above, we:

  1. Got the length of the PHP array by using the count function.
  2. We then subtracted 1 from the size. This is because numeric arrays start at 0, not 1. Therefore, we have to “compensate” for that.
  3. Finally, we divided the last index by 2 and then rounded the number down by using PHP’s floor function.

If you run the snippet above, you will see that var_dump outputs: 2. This is correct, as “Mouse” is the middle element in our array and it is represented by the index 2.

What if there are two middle elements?

In an even-sized array, there will be two middle elements:

In the example above, both Dog and Hamster are “in the middle” of our array. However, if you use the same formula as we used above, the code will still output the index 1:

As you can see, the result is still 1 because the floor function rounded 1.5 down to 1. If you specifically wanted to get the “higher” index in the middle segment, then you would use the ceil function instead of floor:

This works because the ceil function will always round the number upwards.

How to get the middle element of an associative array.

Associative arrays are a bit trickier because we can’t just get the last index and then divide by 2. Instead, we will have to take the following approach:

In the example above, we had to alter our code to make use of the array_keys function. If you run this PHP yourself, you will see that the output is as follows:

The middle element is Ford at index car_1b


Facebook Comments