I have two arrays.
$keys = array(1,2,3,6,9); //note that 9 does not exist as key in the $values array
$values = array('000', '001', '002', '003', '004', '005', '006', '007');
What I would like to do is combine these two arrays in such way that I will get an array which is filtered by the $keys array. You could say that the $values array is reflected to the $keys array which returns a filtered array where only the $values appear if the key of the $values is equal to one of the values in the $keys array.
The question is hard to explain in words so the equivalent of my question above is in the foreach down here:
foreach ($keys as $k){
if (!array_key_exists($k, $values)){ continue; } //prevents $k=9 as key in the $values array
$new[$k] = $values[$k];
}
print_r($new); // Array ( [1] => 001 [2] => 002 [3] => 003 [6] => 006 )
I think it should be possible with a combination of array_merge, array_combine, array_diff and/or array_unique but I can’t seem to figure out the solution. It might be possible that the foreach above is the best way to do this, but I can imagine there must be another great way to do this. So my question basically is: is there another way to accomplish the same goal with less code?
I know what keys exist in the $values array, but I have to reflect those to the $values in a nice way.
$keys_in_values = array_intersect($keys, array_keys($values));
// Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 6 )
Now you might be asking why I am not just using the foreach. Well, the answer is fairly simple. Because I don’t want to. I seems 100% right, but I am just curious if there are other/better solutions. I have some more advanced pieces of code where I would like to use this (recursively) but that is a bit too much for this question since the answer will be the same.
All you need is
array_intersect_key+array_flipOutput