-1

I have multidimensional array and me need to get a minimum value.

Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.

example code

<?php 

$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
    $num = '';
    foreach ($arr as $item => $i) {
        if(is_array($i)){
            NumMin($i);
        }
        else{
                $num .= $i.',';

            }
    }


    $num .= $num;
    return $num;

}
$g = NumMin($arr);
var_dump($g);

I need to get 0

Aksen P
  • 4,564
  • 3
  • 14
  • 27
Ioool
  • 19
  • 1
  • 1
    flatten the array using a technique from [here](https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) then find the min in the array using `min()` – Nick Parsons Nov 29 '19 at 05:37
  • e.g.: `$min = min(...new RecursiveIteratorIterator(new RecursiveArrayIterator($input)));` – Yoshi Nov 29 '19 at 07:32

2 Answers2

2

You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).

And use simply min() function for getting the desired output after.

array_walk_recursive($arr, function($v) use (&$res){
    $res[]=$v; 
});

echo min($res);

Demo

Aksen P
  • 4,564
  • 3
  • 14
  • 27
0
<?php 

$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');

function NumMin($item)
{
    if(intval($item) <= intval($GLOBALS["min"]))
    {
        $GLOBALS["min"] = intval($item); 
    }


}
// The end, $GLOBALS["min"] will have the least value

echo $GLOBALS["min"]; ?>