Reputation: 105
I've an array's
first one:
[0] => 0289 [1] => 0146 [2] => 5519 [3] => 5308 [4] => 5503 [5] => 5357
second one(associative):
[78941] => 5308 [15749] => 5519 [1469156] => 5308 [78971413] => 5357 [418979] => 0289
Need to find keys in second one by first one value. One by one. I did some loop:
for($i=0;$i<=5;$i++){
$keys=array_search($first_array[$i],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
}
But get nothing. What I'am doing wrong?
Addition
The second array is more large than I show here, approximately 10000 values.
I must insert 5 values per file and these values must be uniq, to avoid overlap.
It will be looks like :
$t=0;
for($i=0;$i<=count($second_array);$i++){
$keys=array_search($first_array[$t],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
$t++
if ($t==5){$t=0}
}
Hope it would help.
Upvotes: 2
Views: 2429
Reputation: 942
array_search()
returns the key if it finds the value, and returns false if not found, so if
you want keys, this code is what you want:
$one=array("0"=>"0146","1"=>"5519","2"=>"5308","3"=>"5503","4"=>"5357");
$two=array("78941"=>"5308","15749"=>"5519","1469156"=>"5308","78971413"=>"5357","418979"=>"5357");
$result=array();
for($i=0;$i<=5;$i++){
if(array_search($one[$i],$two))
$result[]=array_search($one[$i],$two);
}
print_r($result);//OR file_put_contents('check.txt',$result,FILE_APPEND)
Upvotes: 0
Reputation: 502
You can do it much simple way using foreach loop
<?php
$i = 0;
foreach($array2 as $key => $value):
if($array1[$i] == $value) {
//$key is the required key, manage your stuffs here.
}
$i++;
endforeach;
?>
Upvotes: 1
Reputation: 737
foreach($first_array as $first_key => $first_value){
foreach($second_array as $second_key => $second_value){
if($first_value == $second_value){
file_put_contents($file_name, $second_key . "\n", FILE_APPEND);
}
}
}
Upvotes: 0
Reputation: 37365
If you need only keys, so just filter them:
$keys = array_intersect($first, array_keys($second));
However, if you want to get both values and keys, then it'll be like:
$keysAndValues = array_intersect_key($second, array_flip($first));
Upvotes: 4