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

How to achieve the following ?

$array1 = array( id => '11', c1 => 'abcd', c2 => '4500', c3 => 'texas' ,c4=>'name' );
$array2 = array( id => '12', c1 => '',    c2 => '4500', c3 => 'arizona', c4=>'' );

I want to compare array 1 and array 2 and copy value from array 1 to array 2 when array 2 value is null. Example from above array i want to copy only c1 & c4 key from array 1 to array 2.

Thanks for the help

share|improve this question
..How did it go? – F4r-20 Mar 22 at 15:51

3 Answers

How about a foreach() loop:

foreach($array1 as $key=>$value){
    if(!$array2[$key]){
        $array2[$key] = $value;
    }
}

And minimized, but a little less readable:

foreach($array1 as $key=>$value){
    $array2[$key] = $array2[$key] ? $array2[$key] : $value;
}
share|improve this answer
+1, actually the most readable way. – raina77ow Mar 22 at 15:25

try this

<?php
$array1 = array( id => '11', c1 => 'abcd', c2 => '4500', c3 => 'texas' ,c4=>'name' );
$array2 = array( id => '12', c1 => '',    c2 => '4500', c3 => 'arizona', c4=>'' );

foreach($array2 as $key =>$value)
{
  if($value == '')
 {
    $array2[$key] = $array1[$key];
 }  
 }  

print_r($array2);
 ?>
share|improve this answer
Thanks perfect. – Rajani Mar 22 at 15:48
@Rajani your welcome mate glad to help you :) – Let's Code Mar 22 at 15:49

Try this :

foreach($array2 as $key=>$value)

if ($value==null) $array2[$key]=$array1[$key];
share|improve this answer

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.