1

I want to compare two arrays in php. I don't want to do it overall, but block by block.
kind of like this

if (a[1] == b[1]){ // do something }
if (a[2] == b[2]){ // do more }

how can i do this without a whole bunch of ifs ?

thanks in advance :)

$a = array(1, 2, 3, 5);
$b = array(1, 1, 1, 1);
$c = array('something', 'something', 'and so forth');
foreach($a as $key => $value){
   if($value == $b[$key]){
      echo $c[$key]. '<br />';
    }
}

my answer. compare 2 arrays, then rune some code. triggered by the blocks that match

2
  • is it intended to run a different block of code every time for each matching case (ie one match case triggers some filesystem calls, another match triggers some database calls, etc)? Or run the same block of code every time? Commented Mar 30, 2011 at 18:48
  • clever question! I want to echo something different for each block. also, somethimes more than one block has to be run Commented Mar 30, 2011 at 18:57

6 Answers 6

1
for($i=0;$i<sizeof(a);$i++){
  if(a[$i]==b[$i]){
    //DO SOMETHING
  }
}
1

want to compare whole array element one by one (assuming both array of same length)

foreach($a as $key => $value){
   if($value == $b[$key])
   {
     // do something
   }
   else
   {
     break;  // stop doing something and break
   }
}

if want to compare some keys

$keys = array('key1', 'key2');
foreach($keys as $value){
   if($a[$value] == $b[$value])
   {
     // true
   }
   else
   {
     // false
   }
}
0
$a = array(1, 3 , 5 ,6 , 7);
$b = array(3, 1, 5, 6, 8 ,9);
$array_size = min(count($a), count($b));

for ($i = 0; $i < $array_size; $i++) {
   if ($a[$i] == $b[$i]) { //you could/should check whether the index is present. 
    //some code
   }
}

This only works for arrays with the same uniformly distributed numerical index.

0
 foreach(array_intersect_assoc($a,$b) as $key => $data)){
     switch($key){
         case 1:
             //something
             break;
         case 2:
             //something
             break;
     }
 }
0
for ($i=0; $i < count($a) && $i < count($b); ++$i) {
    if ($a[$i] == $b[$i]){
      // this is true
    } else {
      // this is false
    }
}
1
  • it should be if($a[$i] == $b[$i]) Commented Mar 30, 2011 at 18:47
0

A good ol for loop should do the trick. You can start with an array of things to do:

$arrayOfThingsToDo = array( "someFunc", "anotherFunc", "yetAnotherFunc" );
$arrayOfA = array( "one", "two", "three" );
$arrayOfB = array( "one", "not two", "three" );

function doCompare($a, $b, $f) {
   $len = count($a);
   for($i = 0; $i < $len; $i++) {
      if($a[$i] == $b[$i]) {
         $f[$i]();
      }
   }
}

Good luck!

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.