PHP Get the minimum and maximum values ​​in a 2D associative array. PHP Get min and max values ​​in a 2D associative array Php find min value in an array

Arrays are one of the convenient structured ways to store information. Each element of such an array has its place, its key and value. The contents of the arrays can be different, such as the base of numbers, names, or simple numeric values. When talking about a number, we can face various kinds of tasks, for example, deriving 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 contains no 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);

We will try to derive the maximum and minimum value this array. For this we will use standard features « max" And " min" respectively:

echo max($my_array); // Output 74 echo min($my_array); // Output 2

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

On the example of an array

$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; // The key of the minimum value echo $max; // Output the result of the maximum value

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

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

Multidimensional arrays differ in 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 some 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 just as real.

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

$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); // Output 74 echo min($out_array); // Output 2

As a small bonus, I will 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 don't mean content, but an example of its structure. Let's say that here you need to display the maximum and minimum values ​​of the "price" keys only.

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); // Output 5 echo max($numbers); // Output 50

This completes the work with arrays in PHP. If suddenly the structure of your array is different and you do not 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, JavaScript view arrays are much simpler, and a simple one-dimensional array would look like this:

var my_array = ;

Indexes are not specified here. In order to find the maximum and minimum value in this array, we will write two of our simple functions:

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)); // Display 74 alert(arrayMin(my_array)); // Output 2

In this case, the numbers "2" and "74" will be displayed 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 the help of which, according to the scheme already familiar to us, we will represent this array as one-dimensional:

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

And with the object Math» get the values ​​we need:

Varmin = Math.min.apply(null, out_array); // Get 2 var max = Math.max.apply(null, out_array); // Get 74 alert(max); // Display 74 On The Screen

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

Well, as usual, a small bonus. Let's consider another multidimensional array with this 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 ​​only from 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 are waiting for you ahead!

I have an array in this format:

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

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

Unlike the 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 with type-casting arrays to integers, which is undefined behavior:

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

My statement above about type-casting was wrong. Actually min() and max() work on arrays, but not how the OP needs them to work. When using min() and max() with multiple arrays or an array of array elements, the elements are compared 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 */

The OP translated into the problem shows why using min() and max() directly seems to give the correct result. The first elements of the array are id , so min() and max() compare them first, which by the way leads to the correct result because the lowest id is the one with the lowest count and the highest id is the one with the highest count 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 cycles? One is enough 🙂

  1. Get the first element by counting the count of both $min and max
  2. iterate over the rest, compare counter with each $min and $max, if less/greater, assign 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 that 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, not the 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)

/*** Retrieve a column from a 2D array with an optional select over another column * * @param $ aArray to retrieve from * @param $ aColName the name of the column to retrieve e.g. "O_NAME" * @param $ aColTest (Optional) The name of the column to run the test on, eg. "O_ID" * @param $aTest (optional) string for test ex. ">=10", "== "".$Toto. """ * @return 1D array with just extracted column * @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


I have an array like this:

Array (0 => array ("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200",), 1 => array ("id" => "20110209172747", "Date" => "2011-02-09", "Weight" => "180",), 2 => array ("id" => "20110209172827", "Date" => "2011- 02-09", "Weight" => "175",), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195 ",))

I need to extract the minimum and maximum weight values. In this example

$min_value = 175

$max_value = 200

Any help on how to do this? Thank you!


2018-05-01 03:06

Answers:

Option 1: You map the array first to get those numbers (rather than full information):

$array = array_column($array, "weight")

Then you get min and max:

$min = min($numbers); $max = max($numbers);

Option 2. (Only if you don't have PHP 5.5.) Same as option 1, but use array_map to pull out the values:

$numbers = array_map(function($details) ( return $details["Weight"]; ), $array);

Option 3.

Option 4: If you need a minimum of min max, array_reduce() might be faster:

$min = array_reduce($array, function($min, $details) ( return min($min, $details["weight"]); ), PHP_INT_MAX);

It does more than min() s, but they are very fast. PHP_INT_MAX should start at the maximum and get lower and lower. You can do the same for $max , but you'll start from 0 , or -PHP_INT_MAX .


2018-05-01 03:11

Foreach ($array as $k => $v) ( $tArray[$k] = $v["Weight"]; ) $min_value = min($tArray); $max_value = max($tArray);


2018-05-01 03:09

For people using PHP 5.5+ this can be done a lot easier with array_column . No need for those ugly arrays.

How to get max value:

$highest_weight = max(array_column($details, "Weight"));

How to get the minimum value

$lowest_weight = min(array_column($details, "Weight"));


2018-01-24 11:04

It's interesting to note that both of the above solutions use extra storage in the form of arrays (first one of them and second one array) and then you find the min and max using the "extra storage" array. While this might be acceptable in the real world of programming (who gives two bits about "extra" storage?), it would get you a "C" in programming 101.

The problem of finding min and max can be easily solved with just two extra memory slots

$first = intval($input["Weight"]); $min = $first ; $max = $first ; foreach($input as $data) ( $weight = intval($data["Weight"]); if($weight<= $min) { $min = $weight ; } if($weight >$max) ( $max = $weight ; ) ) echo " min = $min and max = $max \n " ;


2018-05-01 06:08

$num = array (0 => array("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200"), 1 => array("id" => "20110209172747", "Date" => "2011-02-09", "Weight" => "180"), 2 => array ("id" => "20110209172827", "Date" => "2011 -02-09", "Weight" => "175"), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195 ")); foreach($num as $key => $val) ( $weight = $val["Weight"]; ) echo max($weight); echo min($weight);


2018-01-10 06:44

array ("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200",), 1 => array ("id" => "20110209172747", " Date" => "2011-02-09", "Weight" => "180",), 2 => array ("id" => "20110209172827", "Date" => "2011-02-09", "Weight" => "175",), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195",),) ; foreach ($array as $key => $value) ( ​​$result[$key] = $value["Weight"]; ) $min = min($result); $max = max($result); echo "The array in Minnumum number:".$min."
"; echo " The array in Maximum number:".$max."
"; ?>


2017-11-11 19:33

$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21 ,21,1,12,1,5); asort($Location_Category_array); $count=array_count_values($Location_Category_array);//Counts the values ​​in the array, returns associatve array print_r($count); $maxsize = 0; $maxvalue = 0; foreach($count as $a=>$y)( echo "
".$a."=".$y; if($y>=$maxvalue)( $maxvalue = $y; if($a>$maxsize)( $maxsize = $a; ) ) ) echo "
max = ".$maxsize;

getkey(9)

I have an array like this:

Array (0 => array ("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200",), 1 => array ("id" => "20110209172747", "Date" => "2011-02-09", "Weight" => "180",), 2 => array ("id" => "20110209172827", "Date" => "2011- 02-09", "Weight" => "175",), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195 ",))

I need to extract the minimum and maximum weight values. In this example

$min_value = 175

$max_value = 200

Any help on how to do this? Thank you!

Answers

For people using PHP 5.5+ this can be done a lot easier with array_column . No need for those ugly arrays.

How to get max value:

$highest_weight = max(array_column($details, "Weight"));

How to get the minimum value

$lowest_weight = min(array_column($details, "Weight"));

Option 1: First you map the array to get those numbers (and not the complete information):

$array = array_column($array, "weight")

Then you get min and max:

$min = min($numbers); $max = max($numbers);

Option 2. (Only if you don't have PHP 5.5.) Same as option 1, but use array_map to pull out the values:

$numbers = array_map(function($details) ( return $details["Weight"]; ), $array);

Option 3.

Option 4: If you only need min OR max, array_reduce() might be faster:

$min = array_reduce($array, function($min, $details) ( return min($min, $details["weight"]); ), PHP_INT_MAX);

This makes more min() s, but they are very fast. PHP_INT_MAX should start at the maximum and get lower and lower. You can do the same for $max , but you'll start with 0 or -PHP_INT_MAX .

array ("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200",), 1 => array ("id" => "20110209172747", " Date" => "2011-02-09", "Weight" => "180",), 2 => array ("id" => "20110209172827", "Date" => "2011-02-09", "Weight" => "175",), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195",),) ; foreach ($array as $key => $value) ( ​​$result[$key] = $value["Weight"]; ) $min = min($result); $max = max($result); echo "The array in Minnumum number:".$min."
"; echo " The array in Maximum number:".$max."
"; ?>

Foreach ($array as $k => $v) ( $tArray[$k] = $v["Weight"]; ) $min_value = min($tArray); $max_value = max($tArray);

quickly print five max and min numbers from array without using sort array in php :-

List of seven highest temperatsures:-"; $m= max($array); for($i=1; $i<7 ; $i++) { $m[$i]=max(array_diff($array,$m)); } foreach ($m as $key =>$value) ( ​​echo " ".$value; ) echo "
List of seven lowest temperatures: "; $mi= min($array); for($i=1; $i<7 ; $i++) { $mi[$i]=min(array_diff($array,$mi)); } foreach ($mi as $key =>$value) ( ​​echo " ".$value; ) ?>

How about without using a predefined function like min or max ?

$arr = ; $val = $arr; $n = count($arr); for($i=1;$i<$n;$i++) { if($val<$arr[$i]) { $val = $val; } else { $val = $arr[$i]; } } print($val);

It's interesting to note that both of the above solutions use extra storage in the form of arrays (first one of them and second one array) and then you find the min and max using the "extra storage" array. While this might be acceptable in the real world of programming (who gives two bits about "extra" storage?), it would get you a "C" in programming 101.

The problem of finding min and max can be easily solved with just two extra memory slots

$first = intval($input["Weight"]); $min = $first ; $max = $first ; foreach($input as $data) ( $weight = intval($data["Weight"]); if($weight<= $min) { $min = $weight ; } if($weight >$max) ( $max = $weight ; ) ) echo " min = $min and max = $max \n " ;

$num = array (0 => array("id" => "20110209172713", "Date" => "2011-02-09", "Weight" => "200"), 1 => array("id" => "20110209172747", "Date" => "2011-02-09", "Weight" => "180"), 2 => array ("id" => "20110209172827", "Date" => "2011 -02-09", "Weight" => "175"), 3 => array ("id" => "20110211204433", "Date" => "2011-02-11", "Weight" => "195 ")); foreach($num as $key => $val) ( $weight = $val["Weight"]; ) echo max($weight); echo min($weight);

Here are some ways remove element from array with javascript .

All described methods do not change the original array and create a new one instead.

If you know the element index

Let's say you have an array and you want to remove the element at position i .

One way is to use slice() :

const items = ["a", "b", "c", "d", "e", "f"] const i = 3 const filteredItems = items.slice(0, i-1).concat(items. slice(i, items.length)) console.log(filteredItems)

slice() creates a new array with the indices it receives. We simply create a new array - from the beginning to the index we want to remove, and concatenate another array from the first position following the one we removed to the end of the array.

If you know the meaning

In this case one a good option- use filter() which offers more declarative an approach:

const items = ["a", "b", "c", "d", "e", "f"] const valueToRemove = "c" const filteredItems = items.filter(item => item !== valueToRemove) console.log(filteredItems)

This uses the ES6 arrow functions. You can use traditional features to support older browsers:

const items = ["a", "b", "c", "d", "e", "f"] const valueToRemove = "c" const filteredItems = items.filter(function(item) ( return item != = valueToRemove )) console.log(filteredItems)

or you can use Babel and convert the ES6 code back to ES5 to make it more readable for older browsers, but write modern JavaScript in your code.

Deleting multiple items

What if instead of one element you want to remove many elements?

Let's find the simplest solution.

By index

You can just create a function and remove elements sequentially:

const items = ["a", "b", "c", "d", "e", "f"] const removeItem = (items, i) => items.slice(0, i-1).concat (items.slice(i, items.length)) let filteredItems = removeItem(items, 3) filteredItems = removeItem(filteredItems, 5) //["a", "b", "c", "d"] console. log(filteredItems)

By value

You can look for an include inside a callback function:

const items = ["a", "b", "c", "d", "e", "f"] const valuesToRemove = ["c", "d"] const filteredItems = items.filter(item => !valuesToRemove.includes(item)) // ["a", "b", "e", "f"] console.log(filteredItems)

Avoid mutating the original array

splice() (not to be confused with slice()) mutates the original array and should be avoided.

(PHP 4, PHP 5, PHP 7)

min - Finds the smallest value

Description

If only one is passed as arguments - an array of numbers, min() returns the smallest of them. If the first argument is an integer or a 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 to an integer ( integer) as if it is equal to 0 , but a few 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 whatever parameter is considered "smallest" according to the standard comparison rules. If multiple values different type 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" is treated as 0 when compared to an int
// 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, then it will be compared with the rest
// using the FALSE rule< TRUE, учитывая остальные типы аргументов
// In the example above, -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's "less than" TRUE
$val = min(0 , TRUE ); // 0
?>

2023 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.