PHP Exercises: Create a new array length 3 from a given array using the elements from the middle of the array
103. New Array from Middle Elements
Write a PHP program to create a new array length 3 from a given array (length atleast 3) using the elements from the middle of the array.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{
// Calculate the index of the middle element in the array
$middleIndex = sizeof($numbers) / 2;
// Return a new array containing the three elements around the middle of the input array
return [$numbers[$middleIndex - 1], $numbers[$middleIndex], $numbers[$middleIndex + 1]];
}
// Call the 'test' function with an array [1, 5, 7, 9, 11, 13] and store the result in $result
$result = test([1, 5, 7, 9, 11, 13]);
// Print the new array containing the three elements around the middle using 'implode' and 'echo'
echo "New array: " . implode(',', $result);
?>
Sample Output:
New array: 7,9,11
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to extract the middle three elements from an array and create a new array from them.
- Write a PHP function to determine the central segment of an array of odd length and return that subsection.
- Write a PHP program to slice out the middle portion of an array using calculated index positions.
- Write a PHP script to accept an array of integers and output a new array consisting solely of the median elements.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to create a new array from two give array of integers, each length 3.
Next: Write a PHP program to find the largest value from first, last, and middle elements of a given array of integers of odd length (atleast 1).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.