- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP program to find the maximum element in an array
To find the maximum element in an array, the PHP code is as follows −
Example
<?php function get_max_value($my_array){ $n = count($my_array); $max_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($max_val < $my_array[$i]) $max_val = $my_array[$i]; return $max_val; } $my_array = array(56, 78, 91, 44, 0, 11); print_r("The highest value of the array is "); echo(get_max_value($my_array)); echo("
"); ?>
Output
The highest value of the array is91
A function named ‘get_max_value()’ is defined, that takes an array as parameter. Inside this function, the count function is used to find the number of elements in the array, and it is assigned to a variable −
$n = count($my_array);
The first element in the array is assigned to a variable, and the array is iterated over, and adjacent values in the array are compared, and the highest value amongst all of them is given as output −
$max_val = $my_array[0]; for ($i = 1; $i < $n; $i++) if ($max_val < $my_array[$i]) $max_val = $my_array[$i]; return $max_val;
Outside the function, the array is defined, and the function is called by passing this array as a parameter. The output is displayed on the screen −
$my_array = array(56, 78, 91, 44, 0, 11); print_r("The highest value of the array is"); echo(get_max_value($my_array));
Advertisements