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
function test($nums)
 { 
            $max = max($nums);

            return [$max, $max, $max, $max];
    
 }   

$a = [10, 20, -30, -40];

echo "Original array: " . implode(',', $a) . "\n";

$result = test($a);

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?



PHP: Tips of the Day

$_REQUEST: This SuperGlobal Variable is used to collect data submitted by a HTML Form

Example:

This code save in a php file and run in the browser.

<!DOCTYPE html> 
<html> 
<body> 
  
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> 
 NAME: <input type="text" name="user"> 
 <button type="submit">SUBMIT</button> 
</form> 
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    $name = htmlspecialchars($_REQUEST['user']); 
    if(empty($name)){ 
        echo "Name is empty"; 
    } else { 
        echo $name; 
    } 
} 
?> 
</body> 
</html> 

Output:

Owen