CanadianJeff
CanadianJeff

Reputation: 39

PHP 2 Arrays Get Values From Both Arrays

I dont want to merge or intersect or diff I just want to get both values from both arrays with matching keys regardless of values matching or not.

example data

array1 ( 0 => 'a', 1 => 'b' )
array2 ( 0 => 'a', 1 => 'c' )

foreach

echo "Key: ".$key." Value1: ".$v1." Value2: ".$v2."";

I would like this as the output

Key: 0 Value1: a Value2: a
Key: 1 Value1: b Value2: c

Upvotes: 0

Views: 41

Answers (2)

Amit.S
Amit.S

Reputation: 441

$array1= array( 0 => 'a', 1 => 'b' );
$array2=array ( 0 => 'z', 1 => 'c' );
foreach ($array1 as $k=>$val){
   //safe in case of key does't exist in second array
   if(array_key_exists($k,$array2))
     echo $k . " Value1: ".$val ." Value2: ". $array2[$k].'<br>';
   else
     echo $k . " Value1: ".$val
}

Upvotes: 0

Hayden Schiff
Hayden Schiff

Reputation: 3330

If both arrays have the exact same keys, you can iterate through one of them while printing values from both.

foreach ($array1 as $key => $val) {
   echo "Key: ".$key." Value1: ".$array1[$key]." Value2: ".$array2[$key];
}

Upvotes: 2

Related Questions