Thursday, December 26, 2024
Google search engine
HomeLanguagesPHP Find Min Value From Multidimensional Array

PHP Find Min Value From Multidimensional Array

If you are working with array of multidimensional. And you have to find the lowest/minimum/smallest value in multidimensional array by its key and value. Then you are looking for the right tutorial, in this tutorial you will learn how to find the lowest/min/smallest value in a multidimensional array.

How to Get Min Value in Multidimensional Array By Key Value

Here are some simple ways, using which you can find the smallest/least/lowest value in a multidimensional array.

  • Finding the minimum value in a multidimensional array by key
  • Finding the minimum value in a multidimensional array by value

Finding the minimum value in a multidimensional array by key

Here, You can find the minimum value in a multidimensional array by key using the array_column() and min() function.

Here’s an example:

$data = [
  ['id' => 1, 'value' => 10],
  ['id' => 2, 'value' => 5],
  ['id' => 3, 'value' => 15]
];

$column = array_column($data, 'value');
$min_value = min($column);

echo $min_value; // Outputs 5

When you use array_column () function. So this function returns a single column from a multidimensional array. By specifying the key you want to extract as the second parameter, you can extract all values associated with that key across all subarrays And when you have done this, then you have to use the min () function. Which will give you the minimum/lowest/smallest value as you can see in the above example.

Finding the minimum value in a multidimensional array by value

Another way to find the minimum/smallest/lowest value in a multidimensional array, you can use foreach loop with sub-arrays.

Here’s an example:

$data = [
  ['id' => 1, 'value' => 10],
  ['id' => 2, 'value' => 5],
  ['id' => 3, 'value' => 15]
];

$min_value = $data[0]['value'];
foreach ($data as $sub_array) {
  if ($sub_array['value'] < $min_value) {
    $min_value = $sub_array['value'];
  }
}

echo $min_value; // Outputs 5

In the example above, you initialize the minimum value with the first value in the array and then use a foreach loop to iterate over all the subarrays. And then in each sub-array compare the ‘value’ key with the current minimum value and if you find a smaller value then update the minimum value.

Conclusion

That’s it, In this tutorial, you have learned how to find the minimum value in a multidimensional array using array_column(), min(), foreach loop and sub_array() function.

Recommended Tutorials

RELATED ARTICLES

Most Popular

Recent Comments