w3resource

PHP Exercises: Find the largest value from first, last, and middle elements of a given array of integers of odd length


104. Largest from First, Last, and Middle

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).

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
 { 
    // Store the value of the first element in a variable named $first
    $first = $numbers[0];
    
    // Store the value of the middle element in a variable named $middle_ele
    $middle_ele = $numbers[sizeof($numbers) / 2];
    
    // Store the value of the last element in a variable named $last_ele
    $last_ele = $numbers[sizeof($numbers) - 1];
    
    // Initialize a variable named $max_ele with the value of $first
    $max_ele = $first;

    // Check if $middle_ele is greater than $max_ele, update $max_ele if true
    if ($middle_ele > $max_ele)
    {
        $max_ele = $middle_ele;
    }

    // Check if $last_ele is greater than $max_ele, update $max_ele if true
    if ($last_ele > $max_ele)
    {
        $max_ele = $last_ele;
    }

    // Return the maximum value among the three elements
    return $max_ele;
 }   

// Call the 'test' function with different arrays and print the results
echo test([1]) . "\n";
echo test([1,2,9]) . "\n";
echo test([1,2,9,3,3]) . "\n";
echo test([1,2,3,4,5,6,7]) . "\n";
echo test([1,2,2,3,7,8,9,10,6,5,4]) . "\n";
?>

Sample Output:

1
9
9
7
8

Flowchart:

Flowchart: Find the largest value from first, last, and middle elements of a given array of integers of odd length.

For more Practice: Solve these Related Problems:

  • Write a PHP script to compare the first, middle, and last elements of an odd-length array and return the maximum.
  • Write a PHP function to extract the boundary and central elements from an array and output the largest among them.
  • Write a PHP program to compute and compare three key elements (first, center, last) and display the highest value.
  • Write a PHP script to use conditional operators to determine the largest value among the first, middle, and last numbers in an array.

Go to:


PREV : New Array from Middle Elements.
NEXT : New Array from First Two Elements.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.