Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a function in php:

function cmp_key($lst){
    $itersect_size = count(array_intersect($zset, $lst)); //zset is a list which i have
    return $intersect_size,-count($lst)
}

and then this code in python:

list_with_biggest_intersection = max(iterable,key = cmp_key)

how can i do the above line of code in php given that i want to use the php function cmp_key as the key for the max function...

share|improve this question
So what is $zset? It's not passed into the PHP function so I don't see how this code works, also what does the cmp_key function return? – Dale Jun 16 at 6:31

2 Answers

up vote 0 down vote accepted

Duplicating @mgilson's answer in Python, here's the equivalent in PHP.

function cmp_key($set, $list) {
  return count(array_intersect($set, $list));
}

// This iterates over all lists and compares them with some
// original list, here named $set for consistency with the other example.
$largest = NULL;
foreach ($lists as $list) {
  if (!isset($largest)) {
    $largest = array('list' => $list, 'count' => cmp_key($set, $list));
  }
  else {
    $count = cmp_key($set, $list);
    if ($count > $largest['count']) {
      $largest = array('list' => $list, 'count' => $count);
    }
  }
}
$list_with_biggest_intersection = $largest['list'];
share|improve this answer
sweet and simple, it works! – user2433215 yesterday
Great! Glad to help. – jordojuice yesterday

Call the function to pass the return value as parameter of max function.

list_with_biggest_intersection = max(iterable, cmp_key($lst));
share|improve this answer
Can you please see my previous post: stackoverflow.com/questions/16963958/most-of-in-python I want to do something similar in php @Nagarjun – user2433215 Jun 16 at 7:16
I am not good at python, probably @jordojuice's answer is what you are looking for. – Nagarjun 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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