Hi guys!
Im trying to get the ighest value from any array coming from mysql query.
What i've till now is it!

class vfsClass{

function localvfs() {
        try {
            $sql = $this->link->prepare("select  Vfs_ID from tbl_track order by id asc");
            $sql->execute();
            $rs = $sql->fetchAll(PDO::FETCH_ASSOC);
            return $rs;
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

}   

$q = new vfsClass();
$qr = $q->localvfs();

 foreach ($qr as $key => $value)
 {
     echo $key. '<br>';
    foreach ($value as $key1 => $value1)
     {
         echo "$key1: $value1 <br>";
     }
 }

What i get from this loop or output for this query is

0
Vfs_ID: PRP1438299
1
Vfs_ID: TRC1107224
2
Vfs_ID: TRC1107224
3
Vfs_ID: TRT1458445
4
Vfs_ID: TRR148864
5
Vfs_ID: TRR1463373
6
Vfs_ID: TRR1045837
7

With this loop, i can get each value inside of array, but im trying to get the ighest value of $key,like i want to echo only 7.
So how do i do that.
I tried use the function get_highest() but dint work well maybe i used in wrong way!
Can someone help me with this.
Waiting ear from you guys.
Regards

Recommended Answers

All 7 Replies

Or use recursion, maybe sometnihg like this (not thoroughly tested, just to show the concept):

function findMax($array, $curMax) {
    foreach($array as $val) {
        if(is_array($val)) {
            $curMax = findMax($val, $curMax);
        } else {
            if($curMax < $val) {
                $curMax = $val;
            }
        }
    }
    return $curMax;
}

// Usage
arr[0][0] = 53;
$arr[0][1] = 99;
$arr[0][2] = 36;
$arr[0][4] = 2;
$arr[1] = 9;
$arr[2] = 6;
$arr[3] = 39;
$arr[4][0] = 19;
$arr[4][1] = 59;
$arr[4][2] = 4;
$arr[5] = 56;
$arr[6] = 50;
$arr[7] = 8;
$arr[8] = 53;
$arr[9] = 37;
$arr[10] = 151;

$max = 0;

echo 'Max is: ' . findMax($arr, $max);

Hi Broj1, i can see your idea, but this not going work with multdimensional array.
this is for simple array.

Have you tried it? It works with the above two dimensional array.

Hi guys i salved it! with this function example

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;
}
$dimensional = array(
    7,
    array(3, 5),
    array(5, 4, 7, array(3, 4, 6), 21),
    14,
    2,
    array(5, 4, 3)
    );

$max = recursive_array_max($dimensional);

echo "<p>The maximum value was: {$max}</p>";

if someone in future have some problem just replace $qr on $a

Thanks all

This should work too:

$max = max(array_map('max', $dimensional));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.