0

I have keys array and values array.

$keys = [
   0 => 'Test'
   1 => 'John'
   ...
   22 => 'Kate'
   23 => 'Bob'
]

I run an array_filter($values) to clear out unwanted empty values, then I end up with something like this

$values = [
   1  => '$3'
   22 => '$10'
   23 => '$50'
]

My goal is achieving

[
  'John' => '$3',
  'Kate' => '$10',
  'Bob'  => '$50'
]

Is there a way to map it this way without creating a for loop and a new array to assign each index individually?

I tried using array_intersect_key but couldn't get close at all.

Edit: My version looks like below but I'm sure there are better ways:

$selectedCols = array_intersect_key($keys, array_flip(array_keys($values)));
array_combine($selectedCols, $values);
0

1 Answer 1

2

You should first combine the two arrays using array_combine (https://www.php.net/manual/en/function.array-combine.php), then apply array_filter on the result. That should do it.

array_filter(array_combine($keys, $filters));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.