w3resource

PHP Exercises: Find out the maximum element between the first or last element in a given array of integers, replace all elements with maximum element

PHP Basic Algorithm: Exercise-92 with Solution

Write a PHP program to find out the maximum element between the first or last element in a given array of integers ( length 4), replace all elements with maximum element.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($nums)
 { 
    // Find the maximum value in the array using the 'max' function
    $max = max($nums);

    // Return a new array containing four copies of the maximum value
    return [$max, $max, $max, $max];
 }   

// Create an array $a with some numeric values
$a = [10, 20, -30, -40];

// Print the original array as a string using 'implode' and 'echo'
echo "Original array: " . implode(',', $a) . "\n";

// Call the 'test' function with the array $a and store the result in $result
$result = test($a);

// Print the new array with four copies of the maximum values using 'implode' and 'echo'
echo "New array with maximum values: " . implode(',', $result);
?>

Sample Output:

Original array: 10,20,-30,-40
New array with maximum values: 20,20,20,20

Flowchart:

Flowchart: Find out the maximum element between the first or last element in a given array of integers, replace all elements with maximum element.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to reverse a given array of integers and length 5.
Next: Write a PHP program to create a new array containing the middle elements from the two given arrays of integers, each length 5.

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.