Thursday, 30 August 2018

PHP array_search with associative array

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.

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));

0 comments:

Post a Comment