PHP Get the minimum and maximum values ​​in a two-dimensional associative array. Min - Finds the smallest Php value the number of minimum values ​​in the array

(PHP 4, PHP 5, PHP 7)

min — Finds the smallest value

Description

If only one argument is passed - an array of numbers, min() returns the smallest of them. If the first argument is an integer or float, then there must be at least one more. In this case the function min() will return the smallest of them.

Comment:

Values ​​of different types are compared using standard comparison rules. For example, a non-numeric string ( string) will be compared with an integer ( integer) as if it were equal 0 , but several lines ( string) will be compared alphabetically. The return value will retain the original type of the variable, without conversion.

Return values

Function min() returns the value of the parameter that is considered the "smallest" according to standard comparison rules. If several values ​​of different types are equal to each other (i.e. 0 And "abc"), then the first one will be returned.

Examples

Example #1 Usage example min()

echo min(2, 3, 1, 6, 7); // 1
echo min (array(2 , 4 , 5 )); // 2

// The string "hello", when compared with int, is treated as 0
// Since both values ​​are equal, the order of the parameters determines the result
echo min(0, "hello"); // 0
echo min ("hello" , 0 ); // hello

// Here we compare -1< 0, поэтому -1 является наименьшим значением
echo min ("hello" , - 1 ); // -1

// When comparing arrays of different lengths, min will return the shorter one
$val = min (array(2 , 2 , 2 ), array(1 , 1 , 1 , 1 )); // array(2, 2, 2)

// Multiple arrays of the same length are compared from left to right
// for this example: 2 == 2, but 4< 5
$val = min (array(2 , 4 , 8 ), array(2 , 5 , 1 )); // array(2, 4, 8)

// If an array and a non-array are compared, the array will never be returned
// since arrays are considered larger than all other values
$val = min ("string" , array(2 , 5 , 7 ), 42 ); //string

// If one argument is NULL or boolean, it will be compared with the others
// using the FALSE rule< TRUE, учитывая остальные типы аргументов
// In the example given, -10 and 10 are treated as TRUE
$val = min (- 10 , FALSE , 10 ); // FALSE
$val = min (- 10 , NULL , 10 ); // NULL

// on the other hand, 0 is treated as FALSE, so it is "less" than TRUE
$val = min(0, TRUE); // 0
?>

Arrays are one of the convenient structured ways to store information. Each element of such an array has its own place, its own key and value. The contents of arrays can be different, such as, for example, a database of numbers, names, or simple numeric values. Speaking of numbers, we may be faced with various kinds of tasks, for example, deducing the maximum or minimum value. Today we will talk about how this is solved in different programming languages.

Finding the largest and smallest value of a one-dimensional array in PHP

All arrays differ in their structure. Consider two simple one-dimensional arrays, one of which does not contain keys:

$my_array = array(22, 24, 37, 74, 23, 2, 10);

and one identical to the previous one, but with keys:

$my_array = array(1 => 22, 2 => 24, 3 => 37, 4 => 74, 5 => 23, 6 => 2, 7 => 10);

Let's try to display the maximum and minimum values ​​of this array. To do this we will use standard functions " max" And " min" respectively:

Echo max($my_array); // Print 74 echo min($my_array); // Print 2

If we take a closer look at the second array, then as a result we can get the key of the maximum or minimum values.

Using an array as an example

$my_array = array(1 => 22, 2 => 24, 3 => 37, 4 => 74, 5 => 23, 6 => 2, 7 => 10);

it will look like this:

$max = array_keys($my_array, max($my_array)); $max = $max;// Maximum value key $min = array_keys($my_array, min($my_array)); $min = $min; // Minimum value key echo $max; // Print the result of the maximum value

Accordingly, the maximum value key is “4”, and the minimum value is “6”.

Finding the largest and smallest value of a multidimensional array in PHP

Multidimensional arrays are distinguished by their nesting. For example, a two-dimensional array would look like this without the keys:

$my_array = array(array(22, 24, 37), array(74, 23, 2), array(10));

And, accordingly, with certain keys:

$my_array = array(array(1 => 22, 2 => 24, 3 => 37), array(4 => 74, 5 => 23, 6 => 2), array(7 => 10));

In this case, finding the maximum and minimum values ​​is a little difficult, but also possible.

First, in order to find the maximum and minimum here, we transform the array into a one-dimensional one:

$out_array = array(); foreach($my_array as $sub_array) ( $out_array = array_merge($out_array, $sub_array); )

The design works for both options above. And then, following the example of a one-dimensional array, we will display the data we need:

Echo max($out_array); // Print 74 echo min($out_array); // Print 2

As a small bonus, I’ll give an example of another popular two-dimensional array:

$my_array = array(array("id" => "1", "date" => "2018-03-19", "price" => "5",), array ("id" => "2" , "date" => "2018-03-19", "price" => "50",), array ("id" => "3", "date" => "2018-03-19", " price" => "25",));

By popularity I do not mean the content, but an example of its structure. Let's say that here you need to output the maximum and minimum values ​​of only the “price” keys.

The first thing you need in this case is to get a new array with only this data:

$numbers = array_column($my_array, "price");

Echo min($numbers); // Print 5 echo max($numbers); // Print 50

This completes the work with arrays in PHP. If suddenly the structure of your array is different and you don’t know how to process it, ask the appropriate question in the comments, I will try to help you.

Finding the largest and smallest value of a one-dimensional array in JavaScript

Unlike PHP, the type of arrays in JavaScript is much simpler, and a simple one-dimensional array will look like this:

Var my_array = ;

No indexes are indicated here. In order to find the maximum and minimum values ​​in this array, we will write two simple functions of our own:

Function arrayMax(array) ( return array.reduce(function(a, b) ( return Math.max(a, b); )); ) function arrayMin(array) ( return array.reduce(function(a, b) ( return Math.min(a, b); )); )

which are used to find the values ​​we need. The usage is also simple:

Alert(arrayMax(my_array)); // Print 74 alert(arrayMin(my_array)); // Print 2

In this case, the numbers “2” and “74” will be displayed on the screen as the minimum and maximum values ​​of the array.

Finding the largest and smallest value of a multidimensional array in JavaScript

Multidimensional arrays in JavaScript are just as simple, and they look like this:

Var my_array = [ , , ];

Let's try to find the maximum and minimum here. To begin with, we will write a function with which, according to the scheme we are already familiar with, we will represent this array as one-dimensional:

Var out_array = ; my_array.forEach(function(v) ( Array.prototype.push.apply(out_array, v); ));

And using the object " Math"we get the values ​​we need:

Var min = Math.min.apply(null, out_array); // Get 2 var max = Math.max.apply(null, out_array); // Get 74 alert(max); // Print 74 on screen

In fact, instead of the object " Math“You can use our functions used in the version with a one-dimensional array, but so that you understand that any problem can be solved in several ways - here I have given a slightly different solution.

Well, as per tradition – a small bonus. Let's consider another multidimensional array with the following structure:

Var my_array = [["One", "2018-03-19", 5], ["Two", "2018-03-19", 50], ["Three", "2018-03-19", 25 ], ];

As we can see, the numeric values ​​in each array are in third place. Let's write some code and get the corresponding values ​​from just this data:

Var min = +Infinity; var max = -Infinity; my_array.forEach(function(item) ( if(+item< min) { min =+ item; // Ищем минимальное значение } }); my_array.forEach(function(item) { if(+item >max) ( max =+ item; // Looking for the maximum value ) )); alert(min+" "+max); // Display the result on the screen

That's all. Don't forget to support the project. A lot of interesting things await you ahead!

I have an array in this format:

Array ( => Array ( => 117 => Networking => 16) => Array ( => 188 => FTP => 23) => Array ( => 189 => Internet => 48))

Is there a good way to get the min and max values ​​of "count"? I could do this using multiple loops, but I thought there might be a better way.

Unlike others, you cannot use the min() / max() functions for this problem, as these functions do not understand the arrays of data (array) passed to them. These functions only work for scalar array elements.

START IMAGE

The reason why using min() and max() seems to give the correct answer is because arrays are type-casting to integers, which is undefined behavior:

The conversion behavior to integer is not defined for other types. Do not rely on any observed behavior as it may change without warning.

My statement above about type-casting was wrong. Actually min() and max() work with arrays, but not in the way the OP needs them to work. When using min() and max() with multiple arrays or an array of array elements, compare elements element by element from left to right:

$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8) /* * first element compared to first element: 2 == 2 * second element compared to second element: 4< 5 * first array is considered the min and is returned */

Translated into the problem, the OP shows why directly using min() and max() seems to give the correct result. The first elements of the array are id , so min() and max() compare them first, by the way, leading to the correct result, because the lowest id is the one that has the lowest count and the highest id is the one that has the highest count.

END EDIT

The correct way is to use a loop.

$a = array(array("id" => 117, "name" => "Networking", "count" => 16), array("id" => 188, "name" => "FTP", " count" => 23), array("id" => 189, "name" => "Internet", "count" => 48)); $min = PHP_INT_MAX; $max = 0; foreach ($a as $i) ( $min = min($min, $i["count"]); $max = max($max, $i["count"]); )

You can use the max() and min() functions.

What did you do with multiple loops? One is enough :)

  1. Get the first element by counting the count of both $min and max
  2. iterate over the rest, compare the count with each $min and $max, if less/greater assign a new count value

You can use the max/min functions as they will return an array containing the maximum/minimum of each index. Your example should return array(189, "Networking", 48) for max . You can then grab the score from this array.

Updating this doesn't work as I ruled out. The man page example is misleading and the example gives the correct result using max, but that's just a coincidence.

It looks like you can't use max() on a 2D array. It just returns the largest array, rather than max() of each index (as stated in several answers).

$count = array(); foreach($arr as $_arr) ( $count = $_arr["count"]; ) var_dump(max($count), min($count));

Is there an equivalent built-in function for this? (even without the possibility testing)

/** * retrieves a column from a 2D array with an optional selection over another column * * @param $ aArray to retrieve from * @param $ aColName name of the column to retrieve, e.g. "O_NAME" * @param $aColTest (optional) column name to run the test, e.g. "O_ID" * @param $aTest (optional) string for test ex. ">=10", "== "". $Toto. "" " * @return 1D array with only the column extracted * @access public * / function extractColFromArray ($aArray, $aColName, $aColTest = "", $aTest = "") ( $mRes = array()); foreach ($aArray as $row) ( if (($aColTest == "") || (eval("return". $row[$aColTest]. $aTest. ";"))) ( $ mRes = $ row [ $ aColName]; ) ) return $ mRes; ) // extractColFromArray