PHP Exercises: Create an array taking two middle elements from a given array of integers of length even
Write a PHP program to create an array taking two middle elements from a given array of integers of length even.
Sample Solution:
PHP Code :
Explanation:
- Function Definition:
- A function named test is defined, which takes an array of numbers called $numbers as a parameter.
- Calculate Middle Index:
- The variable $middleIndex is calculated as sizeof($numbers) / 2, which finds the middle index of the array. This calculation assumes the array has an even number of elements.
- Return Middle Elements:
- The function returns an array containing two elements:
- The element just before the middle: $numbers[$middleIndex - 1].
- The element at the middle: $numbers[$middleIndex].
Output:
New array: 7 9
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to compute the sum of the two given arrays of integers, length 3 and find the array which has the largest sum.
Next: Write a PHP program to create a new array from two give array of integers, each length 3.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics