-1

How to find max value ,return the only one number with the highest value

Here is my code:

<?php 
foreach($graphData as $gt) {
    echo $gt['pView'].',';
}
?>

Result:

0,0,0,18,61,106,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 

im try something like this

<?php
    $str = '';
        foreach ($graphData as $gt){
            $str = array($gt['pView'],);}
            $max =max($str);
            if($max == 0){echo '20';}
                else
            {echo $max +20;}
?>

and result is always 20, but shold be 106 + 20

Whats wrong in my code ?

0

3 Answers 3

3

The example code has serious issues. The first is indenting, after fixing which we have

foreach ($graphData as $gt){
    $str = array($gt['pView'],);
}

It should be obvious that this won't really do anything, as it keeps resetting $str to one value in the array after another without doing anything else in the meantime (also, why are you assigning an array to a variable named $str?).

The solution is a straightforward case of iteration:

$max = reset($gt);
foreach ($gt as $item) {
    $max = max($item['pView'], $max);
}

echo "Final result = ".($max + 20);

There are also cuter ways to write this, for example

$max = max(array_map(function($item) { return $item['pView']; }, $gt));

or if you are using PHP 5.5

$max = max(array_column($gt, 'pView'));
1
  • In retrospect, this is actually the best answer. I appreciate the use of array_map and array_column. +1 Commented Aug 6, 2013 at 17:08
1

Try this:

$arr = array();
foreach ($graphData as $gt) {
    array_push($arr, $gt['pView']);
}
$max = max($arr);
if ($max === 0) {
    $max = 20;
}
else {
    $max += 20;
}
echo $max;

As seen in the PHP documentation for max(), the function max can accept a single array of values as an argument. If that's the case, it returns the largest in the array.

2
  • its back 20202020202020202020202020202020202020202020202020202020202020 and alo there is error PHP Warning: max(): When only one parameter is given, it must be an array Commented Aug 6, 2013 at 16:44
  • Ah, I misunderstood your formatting. I edited my answer, see if it works now. Commented Aug 6, 2013 at 16:50
0

You can do:

sort($grafdata);
if($grafdata == 0) {
    echo '20';
} else {
    echo $grafdata + 20;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.