Don Laknath
Don Laknath

Reputation: 55

How to get the intersection of two arrays by keys?

I want to save certain values from $_POST into a file. But I only want values where the key is in the array $lang.

As an example:

$_POST = [1 => "a", 2 => "b", 3 => "c"];
$lang = [2, 3];

With this input I would only want the values from $_POST where the key is in the $lang array.

Expected output would be:

[2 => "b", 3 => "c"]

Right now I'm trying to archive this using ArrayIterator and MultipleIterator, but this loops through both arrays:

$post = new ArrayIterator($_POST);
$lang_array = new ArrayIterator($lang); 
$it = new MultipleIterator;
$it->attachIterator($post);
$it->attachIterator($lang_array);
$fh = fopen('name.php', 'w');
foreach($it as $e) {
    fwrite($fh , $e[1] .'-' . $e[0] );
    fwrite($fh ,"\n" );   
}

So I'm a bit stuck how to solve this problem?

Upvotes: 0

Views: 120

Answers (3)

Rizier123
Rizier123

Reputation: 59701

Since you want the intersection of two arrays by keys you can use array_intersect_key(), but since the keys are values in $lang you just have to flip it first with array_flip(), e.g.

print_r(array_intersect_key($_POST, array_flip($lang)));

Upvotes: 1

Digpal Singh
Digpal Singh

Reputation: 166

two Array combining please try this code:-

<?php
 $fname=array("Peter","Ben","Joe");
 $age=array("35","37","43");
 $c=array_combine($fname,$age);
  print_r($c);
?>

and two array merge :-

<?php
$a1=array("red","green");
 $a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

this code is useful for two array combining and merge

Upvotes: -1

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

Try this :

// Combining both arrays into one.
$combined_array = array_merge($_POST, $lang);
$fh = fopen('name.php', 'w');
foreach($combined_array as $key => $value){
    fwrite($fh , $key .'-' . $value );
    fwrite($fh ,"\n" );
}

Upvotes: 1

Related Questions