Minimum value in php array. PHP Get the minimum and maximum values ​​in a two-dimensional associative array. Removing multiple items

28.02.2024 Memory cards

(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
?>


I have this array:

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: First you collate the array to get those numbers (not the full information):

$numbers = 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 to snatch the values, use array_map:

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

Option 3.

Option 4: If you need min max, array_reduce() may be faster:

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

This does more than min() s, but they are very fast. PHP_INT_MAX should start at a maximum and get lower and lower. You can do the same for $max , but you'll start with 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 much easier with array_column . No need for those ugly arrays.

How to get the maximum 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 additional storage in the form of arrays (first one of them and the second one 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 additional 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 "));


2018-01-10 06:44

foreach($num as $key => $val) ( $weight = $val["Weight"]; ) echo max($weight);
echo min($weight);
"; ?>


2017-11-11 19:33

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."
$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 associate 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;

$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!

get key (9)

I have this array:

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 much easier with array_column . No need for those ugly arrays.

How to get the maximum 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 collate the array to get those numbers (not the full information):

$numbers = 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 to snatch the values, use array_map:

$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 does more than min() s, but they are very fast. PHP_INT_MAX should start at a maximum and get lower and lower. You can do the same for $max , but you'll start with 0 or -PHP_INT_MAX .

foreach($num as $key => $val) ( $weight = $val["Weight"]; ) echo max($weight);
echo min($weight);
"; ?>

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 an array without using sort array in php:-

List of seven highest temperaturs:-"; $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 additional storage in the form of arrays (first one of them and the second one 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 additional 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 "));

Here are some ways remove element from array using JavaScript .

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

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 start to the index we want to delete, and concatenate another array from the first position following the one we deleted to the end of the array.

If you know the meaning

In this case, one good option is to 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 ES6 arrow functions. You can use traditional functions 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.

Removing multiple items

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

Let's find the simplest solution.

By index

You can simply 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 inclusion inside the 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.

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