Menu Close

Combine two arrays

I am using Redis to store key:value data. When I ask for the values by keys I only get the values back. With this simple piece of code I can combine the value and the key together. Let’s look at an example:

  • apple:2,10
  • orange:3,40
  • milk:1,99

When I mget these values from Redis like:

$result = Redis::mget('apple','milk');

I get an numeric array back with numbers as keys:

array:2 [
  0 => "2,10"
  1 => "1,99"

At this point you lost the original key of every value. A way to restore these key:value combinations is to combine two arrays in the following way:

$products = ['apple', 'milk'];
$result = Redis::mget($products);
$combined = array_combine($products, $result);

This will leave you with the complete array:

array:2 [
  "apple" => "2,10"
  "milk" => "1,99"

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *