0

I have two diff array and I want to print these array based on equal condition.

First array

     Array ( 
            [0] => fname 
            [1] => lname 
            [2] => email  
      )

Second array

   Array ( 
           [fname] => john 
           [lname] => notdefined 
           [email] => [email protected] 
           [address] => london 
    )

Now my problem is I want to print values from second array if and only if this array's index match with first array values...

Second array's index == first array's value (I can say this is equality condition for better understanding)

In this case my output should be

   Array (
           [fname] => john
           [lname] => notdefined
           [email] => [email protected]
      )

It should not display address because in first array is not present...

Here this is just sample code but in reality I have a very big array with some additional info also.

2
  • 2
    Flip your first array with array_flip and then make use of array_intersect_key on the two arrays. Commented Feb 10, 2014 at 9:37
  • 1
    @ShankarDamodaran your suggestion worked like charm bro... thanks a lot Commented Feb 10, 2014 at 9:49

2 Answers 2

1

There are plenty of ways, one of them is:

foreach($secArr as $key => $val)
{
     if(in_array($key, $firstArr))
         echo $val;
}

or:

$keys = array_flip($firstArr);
$arr = array_intersect_key($secArr, $keys);
//display $arr;

or:

foreach($firstArr as $key)
{
     if($secArr[$key])
         echo $secArr[$key];
}
Sign up to request clarification or add additional context in comments.

1 Comment

worked like charm with foreach ways.. need to test array_flip
1

Swap first array key and value using array_flip function and Computes the intersection of arrays using keys for comparison using array_intersect_key.

$array1 = array(0 => 'fname',1 => 'lname' ,2 => 'email');
$array1 = array_flip($array1);
$array2 = array( 
       'fname' => 'john', 
       'lname' => 'notdefined', 
       'email' => '[email protected]', 
       'address' => 'london' 
    );

$new = array_intersect_key($array2,$array1);
print_r($new);

working demo

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.