Reputation: 5758
Here is the multi dimensional array
$arr = array(
array(141,151,161),
2,
3,
array(
101,
202,
array(303,404)
)
);
How to find the highest value, which the result in the array above should be 404.
The array depth can may be more than 3.
Here is the code i last tried, but i notice this only can check until 3 depth, i need it can be check unlimited depth
function MaxArray($arr){
foreach($arr as $valueDepth1){
if(is_array($valueDepth1)){
foreach($valueDepth1 as $valueDepth2){
if(is_array($valueDepth2)){
foreach($valueDepth2 as $valueDepth3){
$checingArray[]=$valueDepth3;
}
}else{
$checingArray[]=$valueDepth2;
}
}
}else{
$checingArray[]=$valueDepth1;
}
}
return max($checingArray);
}
Upvotes: 3
Views: 9066
Reputation: 219920
function highest($array) {
foreach($array as $key => $value) {
if (is_array($value)) {
$array[$key] = highest($value);
}
}
sort($array);
return array_pop($array);
}
You can see it in action here: http://codepad.org/4xPFsU1U
Upvotes: 9
Reputation: 1815
getMax($arr);
function getMax($arr) {
foreach($arr as $arrr) {
echo max($arrr[2]);
}
}
Upvotes: 0
Reputation: 11
You have to use recursion, with a single loop. For each element, if it is a number, we compare it with the current highest value, if it is an array we call the function recursively to check the array:
function getHeighestNumber($array = array()) {
static $number = 0;
foreach ($array AS $key=>$value) {
if(is_array($value)) {
$number = getHeighestNumber($value);
} else if($value > $number) {
$number = $value;
}
}
return $number;
}
Upvotes: -2
Reputation: 115
Try This
function MaxRecursive($arr,$maxVal = null)
{
try {
if(! isset($arr) || ! is_array($arr) )
throw new Exception("The array is empty");
for($i=0;$i<count($arr);$i++)
{
if(is_array($arr[$i]))
$maxVal = MaxRecursive($arr[$i],$maxVal);
else
{
if($maxVal == null)
$maxVal = $arr[$i];
if($arr[$i] > $maxVal )
$maxVal = $arr[$i];
}
}
return $maxVal;
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
function MaxArray2($arr)
{
return MaxRecursive($arr,null);
}
Upvotes: 0
Reputation: 12586
Here's a function I found on the first page on google. Search engines is a perfect place to find stuff ;)
function recursive_array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = recursive_array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
Upvotes: 3
Reputation: 22152
This can be a good starting point:
getMax($array)
{
if ( is_array($array) )
{
// NOTE: PHP_MIN doesn't exist. Is just to let you understand the logic
$max = PHP_MIN;
foreach($array as $value)
{
if ( is_array($value) )
$value = getMax($value);
if ($value > $max)
$max = $value;
}
return $max;
}
else
return $array
}
Upvotes: 2
Reputation: 1302
You could try something like this:
$max = -1;
array_walk_recursive($arr, 'arrmax');
function arrmax($item, $key) {
global $max;
$max = ($key > $max) ? $key : $max;
}
echo "Maximum number is : " . $max;
Upvotes: 3