0

I am new to php and still learning the language,

let say I have two array

For Example

Array
(
    [house_id] => 6
    [name] => Lake Villa
    [floor] => 5
    [unit] => 25
)

Array
(
    [house_id] => 6
    [name] => Lake Villa
    [floor] => 5
    [unit] => 25
    [parking_id] => 9
    [resident_count] => 4
)

How do i get the keys of 1st array onto second, what i am saying is, i just need house_id, name, floor, unit from second array and discard rest of the information.

However, they key is not same and dynamic, which means the first array key whatever returned is also present on second but with additional information. The information above is just an example and the keys might varies but whatever key on first array contains on second array too.

I tried this, but isn't working:

foreach($arr1 as $k=>$v) {
    foreach($arr2 as $j=>$w) {
        if(isset($arr2[$k]))
            $arr[$k] = $w;
    }
}
4
  • 3
    what is the expected output? I simply don't understand .. sorry Commented Oct 3, 2012 at 7:36
  • Have you experimented with array_merge? php.net/manual/en/function.array-merge.php Commented Oct 3, 2012 at 7:39
  • -1 This question should be improved by giving expected output. Commented Oct 3, 2012 at 7:51
  • @jack How do i get the keys of 1st array onto second, what i am saying is, i just need house_id, name, floor, unit from second array and discard rest of the information. Commented Oct 3, 2012 at 8:12

6 Answers 6

2

You could use array_intersect_key, to merge the arrays.

$newArray = array_intersect_key($array2, $array1);
Sign up to request clarification or add additional context in comments.

Comments

2

Use array_intersect_key().

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

Code

var_dump(array_intersect_key($array1, $array2));

Comments

1
foreach($arr2 as $key=>$val){
   if(!array_key_exists($key,$arr1))        
   unset($arr2[$key]);
}

2 Comments

would appericiate if you can be done within two array. thanks
I dont think its better then array_intersect_key, but it's alternative.
0

change condition from

if(isset($arr2[$k]))

to

if($arr1[$k] == $arr2[$j])   // it will work.

and isset is used for checking the variable is set or not.

Comments

0

Try this:

foreach($arr2 as $k=>$v) {
    //Check if key is in first array
    if(!isset($arr1[$k])) {
        //Key not in first array, remove from second array. 
        unset($arr2[$k]); 
    }
}

Comments

0

try this

$result_array = array_intersect_key($arr2, $arr1);

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.