-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 ?

Milan Milosevic
  • 413
  • 2
  • 8
  • 19

3 Answers3

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'));
Jon
  • 428,835
  • 81
  • 738
  • 806
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.

theftprevention
  • 5,083
  • 3
  • 18
  • 31
0

You can do:

sort($grafdata);
if($grafdata == 0) {
    echo '20';
} else {
    echo $grafdata + 20;
}
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
guy
  • 40
  • 7