Kristīne Glode
Kristīne Glode

Reputation: 1409

Combining two arrays based on values php

I was wondering, how it is possible to perform function on each array element based on value.

For example, if I have two arrays:

[
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
]

And

$translation = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

How can I get

    [ 
      0 =>  'One', 
      1 =>  'Two', 
      2 =>  'Three',
      3 =>  'Four'
   ]

?

I managed with foreach, but I believe there are some more efficient ways to do that. I tried to play around with array_walk and array_map, but din't get it. :(

Upvotes: 0

Views: 76

Answers (4)

jitendrapurohit
jitendrapurohit

Reputation: 9675

Combine the keys and values of these arrays using array_combine-

$sliced_array = array_slice($translation, 0, count(array1));

array_combine(array_keys($array1), array_values($sliced_array));

1st param gives the keys of arrays and second print the values. Finally combine it with array_combine.

Upvotes: 0

Chuck Norris
Chuck Norris

Reputation: 1123

$toto1 = [
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
];

$toto2 = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

$result = array_slice(array_merge(array_values($toto2), $toto1), 0, count($toto1));

Upvotes: 0

Passionate Coder
Passionate Coder

Reputation: 7294

<?php 
$data = array('gp','mnp','pl','reg');
$translation = array( 'gp' => 'One','mnp' => 'Two','pl' => 'Three','reg' => 'Four','other' => 'Five','fs' => 'Six');
$new  = array_flip($data);// chnage key value pair
$newArr = array();
foreach($new as $key=>$value){
    $newArr[]= $translation[$key];  
}

echo "<pre>";print_r($newArr);

Upvotes: 0

Bert
Bert

Reputation: 2456

<?php

$arr = [
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
];

$translation = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

$output = array_map(function($value)use($translation){
  return $translation[$value];
  }, $arr);

print_r($output);

Output:

Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => Four
)

Upvotes: 1

Related Questions