March 4, 2017

MAX in PHP returning wrong value

Krish’s Question:

I have an array with key and value pair. I’m building this array dynamically and below is the code.

$x[] = array('type_name' => $value->name,
            'percentage'=> intval($percentage));

My intention is to get the maximum value and for that I do

max($x);

However it is returning the wrong value actually the lowest value. Following is my array. Any help would be awesome.

Thanks is advance.

You need to read how the max compares against different types of data. In your case, you are trying to compare against one of the array item i.e. percentage inside one of the item so the function max does not know to do this.

There is an example by Revo in the manual which shows you how to do this.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!