Как найти максимальный элемент массива php

(PHP 4, PHP 5, PHP 7, PHP 8)

maxВозвращает наибольшее значение

Описание

Альтернативная сигнатура (не поддерживается с именованными аргументами):

max(array $value_array): mixed

Замечание:

Значения разных типов будут сравниваться в соответствии со стандартными правилами сравнения.
К примеру, нечисловая строка (string) будет сравниваться с целым числом
(int) так, как будто это 0, а множество
нечисловых строк (string) будут сравниваться алфавитно-цифровым
порядком. Выбранное значение будет возвращено без конвертации типа.

Предостережение

Будьте осторожны при передаче аргументов разных типов, поскольку результат
max() может вас удивить.

Список параметров

value

Любое поддающееся сравнению
значение.

values

Любые поддающиеся сравнению
значения.

value_array

Массив, содержащий значения.

Возвращаемые значения

max() вернёт значение «наибольшего» из элементов массива, в
соответствии со стандартными правилами сравнения. Если несколько разнотипных
значений посчитаются идентичными (например 0 и
'abc'), функция вернёт первое из них.

Ошибки

Если передан пустой массив, функция max()
выбрасывает ошибку ValueError.

Список изменений

Версия Описание
8.0.0 Функция max() теперь в случае возникновения ошибки
выбрасывает ошибку ValueError;
ранее возвращалось значение false и выдавалась ошибка уровня E_WARNING.

Примеры

Пример #1 Пример использования max()


<?php
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5

// 'hello' будет представлено как числовое значение 0.
// Оба параметра имеют одинаковое значение, поэтому результат
// определяется порядком, в котором параметры переданы

echo max(0, 'hello'); // 0
echo max('hello', 0); // hello

// Здесь сравниваются -1 < 0, так что 'hello' больше

echo max('hello', -1); // hello

// В данном случае 0 больше, чем -1, поэтому результат равен 'hello'.

echo max(-1, 'hello'); // hello

// При сравнении массивов, разной длины - max вернёт более длинный

$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// При сравнении массивов одинаковой длины - max будет сравнивать их поэлементно
// слева направо, в данном примере 2 == 2, но 4 < 5

$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// Если передан массив и не массив, в результате всегда будет возвращён массив

$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)

// Если один из аргументов NULL или булево значение, то сравнение с другими
// значениями будет происходить по правилу FALSE < TRUE, вне зависимости от того
// какого типа параметры переданы.
// В примере ниже, -10 трактуется как TRUE

$val = max(-10, FALSE); // -10

// 0 всегда трактуется как FALSE, значит он "меньше чем" TRUE

$val = max(0, TRUE); // TRUE
?>

Смотрите также

  • min() — Находит наименьшее значение
  • count() — Подсчитывает количество элементов массива или Countable объекте

keith at bifugi dot com

6 years ago


The simplest way to get around the fact that max() won't give the key is array_search:

<?php
$student_grades
= array ("john" => 100, "sarah" => 90, "anne" => 100);
$top_student = array_search(max($student_grades),$student_grades); // john
?>

This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:

<?php
$grades_index
= array_flip($student_grades);
$top_student = $grades_index[max($student_grades)]; // anne
?>

To get all the max value keys:

<?php
$top_students
= array_keys($student_grades,max($student_grades)); // john, anne
?>


deoomen

11 months ago


Watch out after PHP 8.0!

Sample code:

<?php
echo max(0,'hello');
?>

Before PHP 8.0 will return int(0) but since PHP 8.0 above code returns string("hello")!!


volch5 at gmail dot com

9 years ago


max() (and min()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1
= new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo
max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17

marcini

14 years ago


Note that max() can compare dates, so if you write something like this:

<?php
$dates
= array('2009-02-15', '2009-03-15');
echo
max($dates);
?>

you will get: 2009-03-15.


costinu

11 years ago


max(null, 0) = null

max(0, null) = 0

Alex Rath

13 years ago


Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max

('7iuwmssuxue', 1); //returns 7iuwmssuxu
 
max('-7suidha', -4); //returns -4?>

But just if it is in front of the String

<?php

  max

('sdihatewin7wduiw', 3); //returns 3?>


ReVo_

8 years ago


Sometimes you could need to get the max from an array which looks like this:

<?php
$arrTest
= array(
    array(
"day" => 1, "b" => 10 ),
    array(
"day" => 2, "b" => 43 ),
    array(
"day" => 3, "b" => 2 ),
    array(
"day" => 4, "b" => -3 ),
    array(
"day" => 5, "b" => 4 ),
    array(
"day" => 6, "b" => -5 )
);
?>
all max functions i see around don't provide a way to get the max value of the values in (example) key "b"

<?php
function maxValueInArray($array, $keyToSearch)
{
   
$currentMax = NULL;
    foreach(
$array as $arr)
    {
        foreach(
$arr as $key => $value)
        {
            if (
$key == $keyToSearch && ($value >= $currentMax))
            {
               
$currentMax = $value;
            }
        }
    }

    return

$currentMax;
}
//                                            array       key
$value = maxValueInArray($arrTest, "b");?>

output: 43


ries at vantwisk dot nl

14 years ago


I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries


johnphayes at gmail dot com

17 years ago


Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true


michaelangel0 at mail.com

15 years ago


Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php

function doublemax($mylist){

 
$maxvalue=max($mylist);

  while(list(
$key,$value)=each($mylist)){

    if(
$value==$maxvalue)$maxindex=$key;

  }

  return array(
"m"=>$maxvalue,"i"=>$maxindex);

}

?>


php at rijkvanwel dot nl

12 years ago


To get the largest key in an array:

<?php
$array
= array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>


info at osworx dot net

4 years ago


Be aware if a array like this is used (e.g. values from a shopping cart):
<?php
Array
(
    [
0] => 142,80
   
[1] => 39,27
   
[2] => 22,80
   
[3] => 175,80
)?>
The result will be: 39,27 and not - as expected - 175,80

So, to find the max value, use integer only like:
<?php
Array
(
    [
0] => 14280
   
[1] => 3927
   
[2] => 2280
   
[3] => 17580
)?>
and you will get the correct result: 17580


sun at drupal dot org

11 years ago


Note that max() throws a warning if the array is empty:

<?php
$a
= array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.


harmor

15 years ago


A way to bound a integer between two values is:

<?php

function bound($x, $min, $max)

{

     return
min(max($x, $min), $max);

}

?>



which is the same as:

<?php

$tmp
= $x;

if(
$tmp < $min)

{

   
$tmp = $min;

}

if(
$tmp > $max)

{

    
$tmp = $max;

}

$y = $tmp;

?>



So if you wanted to bound an integer between 1 and 12 for example:

Input:

<?php

$x
= 0;

echo
bound(0, 1, 12).'<br />';

$x = 1;

echo
bound($x, 1, 12).'<br />';

$x = 6;

echo
bound($x, 1, 12).'<br />';

$x = 12;

echo
bound($x, 1, 12).'<br />';

$x = 13;

echo
bound($x, 1, 12).'<br />';

?>



Output:

1

1

6

12

12


levim at php dot net

10 years ago


<?php
/**
* @param array $array
*
* @return int|null Returns the largest value of the array. Returns NULL if no
*     integers are found.
*/
function array_max_recursive(array $array) {
   
$max = NULL;
   
$stack = array($array);

    do {

$current = array_pop($stack );
        foreach (
$current as $value) {
            if (
is_array($value)) {
               
$stack[] = $value;
            } elseif (
filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
               
// max(NULL, 0) returns NULL, so cast it
               
$max = (int) max($max, $value);
            }
        }

    } while (!empty(

$stack));

    return

$max;
}
?>

- This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way. 
- It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
- It ignores non-array, non-int values.

toon dot baeyens at gmail dot com

11 years ago


A little function for multi-dimensional arrays:
<?php
function amax($array){
    if(
is_array($array)){
        foreach(
$array as $key => $value){
           
$array[$key] = amax($value);
        }
        return
max($array);
    }else{
        return
$array;
    }
}
?>

blackmac01 at gmail dot com

3 years ago


In response to: keith at bifugi dot com

If you want to find the specific key(s) that match the maximum value in an array where the values may be duplicated, you can loop through and perform a simple check:
<?php# Example Array
$a = array(
    
'key1' => 100,
    
'key2' => 90,
    
'key3' => 100,
    
'key4' => 90,
);
# First get the maximum value
$max = max($a);# Create a new array containing all keys which have the max value
foreach($a as $key => $val) {    
     if(
$val === $max) $b[] = $key;
}
# If you want a string list, just do this
$b = implode(' ', $b);
?>

This produces consistent results and will scale well in terms of performance, whereas functions like array_search and array_flip can lead to degraded performance when dealing with large amounts of data.


chris at candm dt org dt uk

1 year ago


A function to return the key of the max value of an array. For multiple max values, it will return the key of first. Change > to >= to get the last.

function array_max_key($arr) {
    $maxkey='';
    $maxval=false;
    array_walk($arr,
        function (&$cval,&$ckey) use(&$maxkey,&$maxval) {
            if ($maxval === false || $cval > $maxval) {
                $maxval = $cval;
                $maxkey = $ckey;
            }
        }
    );
    return $maxkey;
}


Michael Blinn

4 years ago


Be careful using max() with objects, as it returns a reference not a new object.

<?php

$min_date

= date_create('2019-03-05');
$max_date = date_create('2019-03-06');$date_by_reference = max($min_date, $max_date);// $date_by_reference and $max_date are now the same objectecho '$max_date is ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-06'
echo '$date_by_reference is ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-06'date_add($date_by_reference, date_interval_create_from_date_string('1 days')); // Add 1 day to $date_by_reference, changes $max_date tooecho '$max_date is changed ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-07'
echo '$date_by_reference is changed ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-07'?>


Самый простой способ

Разумеется, проще всего получить минимальный и максимальный элементы массива с помощью функций min() и max():

$arr = [8, 4, 12, 9];
$max = max($arr); // 12
$min = min($arr); // 4

Однако на форумах часто просят написать скрипт, не использующий эти функции. Чаще всего этого требуют преподаватели учебных учреждений.

Условия задачи

1. Найти наибольший наименьший элементы в одномерном числовом массиве.
2. Определить номер минимального и максимального элементов заданного одномерного массива.
3. Найти минимальное и максимальное значение в ассоциативном массиве.

Общий принцип поиска элементов

Во всех решениях мы будем использовать одну и ту же логику.

Согласно условию, нам необходимо объявить числовой массив произвольной длины. Также объявим 4 переменные, в которые будем помещать найденные значения и их ключи:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

Далее перебираем массив в цикле и на каждой итерации проверяем, больше ли текущее значение, чем самое большое, что мы находили до этого.

И если больше — будем записывать в $max новое максимальное значение, а в $max_key его ключ. Абсолютно также поступим и с минимальными ключом и значением.

Пример с циклом foreach:

foreach($arr as $k => $v)
{
	if($v > $max)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min)
	{
		$min = $v;
		$min_key = $k;
	}
}

На данном этапе наш код уже будет работать, но это ещё не всё. Попробуем изменить исходный массив и посмотрим на результат:

<?php
$arr = [0, -12];
$max = null;

foreach($arr as $v)
{
	if($v > $max)
		$max = $v;
}

var_dump($max); // -12

Максимальным должно быть число 0, но скрипт вывел -12. Дело в том, что PHP не считает истинным выражение 0 > null, поэтому ноль на первой итерации цикла не записался в переменную $max.

Для решения этой проблемы просто добавим условие, что если $max === null, т.е. если это первая итерация, то в любом случае записываем текущее значение в $min и $max:

<?php
$arr = [0, -12];
$max = null;

foreach($arr as $v)
{
    if($v > $max or $max === null)
        $max = $v;
}

var_dump($max); // -12

Минимальный и максимальный элементы с циклом FOREACH

Решение:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

foreach($arr as $k => $v)
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = $k;
	}
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Минимальный и максимальный элементы с циклом WHILE

Решение 1: счётчик + count()

Цикл будет выполняться до тех пор, пока значение счётчика $i не превысит количество элементов массива.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while($i < count($arr))
{
    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }

	$i++;
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 2: счётчик + isset()

Запускаем вечный цикл while и в каждой итерации цикла проверяем существование следующего элемента с помощью isset(). Если его нет — выходим из цикла оператором break:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while(true)
{
	if(isset($arr[$i]))
	{
		if($arr[$i] > $max or $max === null)
		{
			$max = $arr[$i];
			$max_key = $i;
		}

		if($arr[$i] < $min or $min === null)
		{
			$min = $arr[$i];
			$min_key = $i;
		}
	}
	else
		break;

	$i++;
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 3: list() + each()

Функция each() возвращает ключ и значение текущего элемента массива и смещает его внутренний указатель на единицу. Функция list() используется просто для удобства — с её помощью мы превращаем массив, который возвращает функция each, в две разные переменные:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while(list($k, $v) = each($arr))
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = $k;
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = $k;
	}
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Получился практически аналог foreach. Единственный минус в том, что начиная с PHP 7.2 функция each() объявлена устаревшей.

Решение 4: current() + next()

Это решение похоже на предыдущее с each(). Получаем текущий элемента массива функцией current() и смещаем внутренний указатель массива функцией next(). Получить текущий ключ массива можно с помощью функции key().

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

while($v = current($arr))
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = key($arr);
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = key($arr);
	}

	next($arr);
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Наибольший и наименьший элементы с циклом FOR

Решение 1: счётчик + count()

Вводим счётчик $i и увеличиваем его после каждой итерации. Цикл прекратится как только значение счётчика превысит количество элементов массива.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

for($i = 0; $i < count($arr); $i++)
{
    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 2: счётчик + isset()

В отличие от предыдущего варианта, мы не смотрим на количество элементов массива, а запускаем вечный цикл и в каждой итерации проверяем существование следующего элемента, и если его нет — прерываем цикл командой break:

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;

for($i = 0; true; $i++)
{
	if(!isset($arr[$i]))
		break;

    if($arr[$i] > $max or $max === null)
    {
        $max = $arr[$i];
        $max_key = $i;
    }

    if($arr[$i] < $min or $min === null)
    {
        $min = $arr[$i];
        $min_key = $i;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 3: each() + list()

Функция each() возвращает массив с ключом и значением текущего элемента массива, а list() превращает этот массив в 2 разные переменные. После последнего элемента функция each() вернёт false и цикл прекратит работу.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

for(; list($k, $v) = each($arr);)
{
    if($v > $max or $max === null)
    {
        $max = $v;
        $max_key = $k;
    }

    if($v < $min or $min === null)
    {
        $min = $v;
        $min_key = $k;
    }
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Решение 4: current() + next()

С помощью функции next() смещаем внутренний указатель массива, а функции current() и key() возвращают текущие ключ и значение. Первое и последнее выражение цикла оставляем пустыми.

<?php
$arr = [12, 4, 182, 1, 2.587];
$min = null;
$min_key = null;
$max = null;
$max_key = null;
$i = 0;

for(; $v = current($arr);)
{
	if($v > $max or $max === null)
	{
		$max = $v;
		$max_key = key($arr);
	}

	if($v < $min or $min === null)
	{
		$min = $v;
		$min_key = key($arr);
	}

	next($arr);
}

echo "Min value: $min <br> Min key: $min_key <br>";
echo "Max value: $max <br> Max key: $max_key";

Максимальное значение в ассоциативном массиве

В ассоциативных массивах отсутствует порядок или системность в названиях ключей, поэтому циклы со счётчиками здесь недоступны.

Но мы всё ещё можем использовать цикл foreach и те решения для while и for, где используются функции each() и next(), поскольку они используют не ключи, а внутренний указатель массива.

Here a solution inside an exercise:

function high($sentence)
{
    $alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $alphabet = array_flip($alphabet);

    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        $letters = str_split($word);
        $points = 0;
        foreach ($letters as $letter)
            $points += $alphabet[$letter];
        $score[$word] = $points;
    }

    $value = max($score);
    $key = array_search($value, $score);

    return $key;
}

echo high("what time are we climbing up the volcano");


<?php
echo max(23167);  // 7
echo max(array(245)); // 5

// Строка 'hello', при сравнении с int, рассматривается как 0
// Так как оба значения равны, то порядок параметров определяет результат

echo max(0'hello');     // 0
echo max('hello'0);     // hello

// Здесь мы сравниваем -1 < 0, поэтому 'hello' является наибольшим значением

echo max('hello', -1);    // hello

// При сравнении массивов разной длины, max вернет более длинный

$val max(array(222), array(1111)); // array(1, 1, 1, 1)

// Несколько массивов одинаковой длины сравниваются слева направо
// для этого примера: 2 == 2, но 5 > 4

$val max(array(248), array(251)); // array(2, 5, 1)

// Если сравниваются массив и не-массив, то массив всегда будет возвращен
// так как массивы считаются большими чем все остальные значения

$val max('string', array(257), 42);   // array(2, 5, 7)

// Если один аргумент является NULL или булевым, то он будет сравниваться с остальными
// с использованием правило FALSE < TRUE, учитывая остальные типы аргументов
// В приведенном примере -10 рассматривается как TRUE

$val max(-10FALSE); // -10
$val max(-10FALSE); // -10

// с другой стороны, 0 рассматривается как FALSE, поэтому это "меньше" чем TRUE

$val max(0TRUE); // TRUE
?>

PHP get the max/maximum/largest value from array. This tutorial has the purpose to explain to you several easy ways to find or get the maximum or largest value from an array in PHP.

Here, we will take e.g. PHP gets the maximum value in an array, get the largest number in the array PHP without a function or get the max value from an array in PHP using for loop

PHP find the highest value in an array

To get the maximum value from an array in PHP, you can use the max() function. This function takes an array as its parameter and returns the maximum value in the array.

PHP max() function

The max() function is inbuilt PHP function, which is used to find the numerically maximum or highest value in an array or find maximum or highest value of given specified values.

Syntax

 max(array)  
 or
 max(value1, value2, value3 … valueN)

Example – 1 Get max value in array PHP using max() function

Let’s take the first example, we will use the PHP max() function to find the maximum value in the array. Let’s see the example below:

<?php

$array = [1, 10, 50, 40, 2, 15, 100];

$res = max($array);

print_r($res);

?> 

The output of the above program is: 100

Example 2 – Find largest number in array php without function

Let’s take the second example, in this example, we will find or get the largest or maximum number in array PHP without function. Let’s see the example below:

<?php

$array = array(1000,400,10,50,170,500,45);

$max = $array[0];

foreach($array as $key => $val){

    if($max < $val){

        $max = $val;
        
    }
}	

print $max;

?> 

The output of the above program is: 1000

Example – 3 PHP get max or highest value in array using for loop

Let’s take the third example, to find the maximum or largest or highest value in array PHP without using any function. Let’s look at the examples below:

<?php 

$array = array(500, 20, 55 ,165, 456, 78, 75);


$max = 0;

for($i=0;$i<count($arr);$i++)
 {
    if ($arr[$i] > $max)
	{
        $max = $arr[$i];
    }
}

print $max;

?>

Example – 4 PHP get max or highest value in array using array reduce

We can also use the array_reduce() function to find the maximum value in an array. Here’s an example:

$numbers = array(1, 5, 3, 8, 2);
$max = array_reduce($numbers, function($a, $b) {
    return $a > $b ? $a : $b;
});
echo $max; // Output: 8

In this example, we use the array_reduce() function to iterate over the array and find the maximum value. The function passed as the second parameter to array_reduce() compares two values at a time and returns the larger of the two. The array_reduce() function returns the maximum value, which is then assigned to the $max variable. Finally, we use the echo statement to print the value of $max.

Conclusion

Through this tutorial, we have learned how to find or get max value or elements from array in PHP.

Recommended PHP Tutorials

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

View all posts by Admin

Понравилась статья? Поделить с друзьями:
  • Экономика как найти рыночную стоимость
  • Как найти записанные треки
  • Как найти объем если известна площадь поверхности
  • Как найти бабушку которая заговаривает грыжу
  • Как найти модуль формы в 1с