0

I have a php array

How can I compare all values of this array and filter out values based on custom logic (callback function maybe).

Essentially, I want to compare each array value with every other value within the array and based on some custom logic, either keep the value or remove it from the array

Thanks

2
  • 2
    array_filter comes to mind, or just iterate over the array. Is there anything you have problems with? Commented Feb 28, 2012 at 13:59
  • Hi. array_filter applies the callback to each element of the array. I am looking for something that compares the array elements with each other. Something like usort() which gives you 2 arguments and you decide how the sorting will occur Commented Feb 28, 2012 at 14:05

3 Answers 3

1

Probably you have to do it manually:

function your_callback($a, $b)
{
   return $a != $b;
}    
$array = array(/** Your array here... **/);
$n = count($array);
$filtered = array();
for($i = 0; $i < $n; $i++)
{
   $ok = true;
   for($j = 0; $j < $n; $j++)
   {
      if($j != $i && !your_callback($array[$i], $array[$j])
      {
         $ok = false;
         break;
      }
   }
   if($ok)
      array_push($filtered, $array[$i]);
}
unset($array);
$array = $filtered;

This example will filter unique values of array for example; change your_callback definition to implement other logic.

Sign up to request clarification or add additional context in comments.

Comments

0

You can call array_map, passing your callback as the first argument, and passing your array twice, as the second and the third argument. In the callback function, you loop through the "second" array and return the element if you want.

Comments

0

If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:

if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}

if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);

for($ac=0; $ac<$arr; $ac++){

if($r[$ac]==$anr[$ac]){
$res=$res+5;

}
}
echo $res;
}

Comments

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.