0

I have an associative array like below

[
    [
        'k1' => 'v1',
        'k2' => 'v2'
    ],
    [
        'k1' => 'v1',
        'k2' => 'v2',
        'k3' => 'v3'
    ],
    [
        'k1' => 'v1',
        'k2' => 'v2',
        'k3' => 'v3',
        'k4' => 'v4'
    ]
]

Is it possible to get 3rd array which has maximum key/value pair.

EDIT

Let me clear a bit.

  • array[0] contains 2 key/value pair.
  • array[1] contains 3 key/value pair.
  • array[2] contains 4 key/value pair.

So I need to get array which contains maximum key/value pair.

Thanks in advance

5
  • do you want to get max value of key and max value of value ? or you want to get max value of key and its value ? or max value with its key ? please specify. Commented Dec 19, 2016 at 6:19
  • What is your expected results? Commented Dec 19, 2016 at 6:21
  • I need to get the array with maximum fields i.e (keys/values). Commented Dec 19, 2016 at 6:21
  • @AabirHussain can you please show us your actual array and expected output ? Commented Dec 19, 2016 at 6:22
  • hope my edit would clear the question. @Tiger I can't show you the actual Array becuase it is a huge array with more than 50 key/value pair. Commented Dec 19, 2016 at 6:31

1 Answer 1

1

You can use bellow approach for getting your result :

$array = array(
                array('K1'=>'v1'),
                array('K1'=>'v1','K2'=>'v2'),
                array('K1'=>'v1','K2'=>'v2','K3'=>'v3')
                );
$maxs = array_keys($array, max($array));
print_r($maxs);

It will provide you output as :

Array ( [0] => 2 ) 

Then you can get your key value pairs according to your requirement after passing this maxs array value like this.

$myMaxValue = $array[$maxs[0]];
print_r($myMaxValue);

This provide you below result :

Array ( [K1] => v1 [K2] => v2 [K3] => v3 ) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for max($array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.