0

Quick question, most likely for a veteran will be easy, or maybe im asking for too much.

i have this code for laravel in php, im not fan to do a foreach, is there a better way? i guess should be an existing function that replace my values of arr to the keys match on arr2, but i dont know

Its really important not to change the order.

$arr=  ['filters', 'repeat', 'via', 'type'];
$arr2= [
        'filters' => 'text1',
        'repeat' => 'text2',
        'via' => 'text3',
        'type' => 'text4',
    ];

foreach($arr as $k)
    $res[]=$arr2[$k];

return $res;
Julio Popócatl
  • 712
  • 8
  • 16
  • another way `$res = array_intersect_key($arr2, array_flip($arr));`, so that you don't lose the matching – Kevin May 06 '20 at 08:46

5 Answers5

3

You can do it using array_map.

$arr=  ['filters', 'repeat', 'via', 'type'];
$arr2 = [
    'filters' => 'text1',
    'repeat' => 'text2',
    'via' => 'text3',
    'type' => 'text4',
];

$res = array_map(function($key) use($arr2) {
    return $arr2[$key];
}, $arr);

print_r($res);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
2

You can use Laravel's array_only helper function:

$res = array_only($arr2, $arr);

If you don't want to preserve the keys then you can use the array_values function too:

$res = array_values(array_only($arr2, $arr));
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
2

Yes, two ways:

  1. Use array_values(), assuming the values of $arr are exactly in the same order as the keys in $arr2 and always have the same keys. I'm guessing this is not exactly what you meant, but that's what your example shows. If that's the case, then it is as simple as:
    $res = array_values($arr2)
  1. Use array_map() to map the values of one array (in this case $arr) to a new array ($res):
    $mapper = function($k) use ($arr2) {
        return $arr2[$k];
    };
    $res = array_map($mapper, $arr);

You can then also add handling of cases where $k does not exist in $arr2, e.g. return null and then use array_filter to filter out the null values;

(I did not test this code but generally, this is the approach)

shevron
  • 3,463
  • 2
  • 23
  • 35
2

You can use Collection in Laravel

$res = collect($arr)->map(function ($key) use ($arr2) {
    return $arr2[$key];
})->toArray()
Frank Vu
  • 1,203
  • 1
  • 9
  • 19
1

If you just want the array values you can use the array_values() function.

$arr2= [
        'filters' => 'text1',
        'repeat' => 'text2',
        'via' => 'text3',
        'type' => 'text4',
 ];

$res = array_values($arr2);

This will result in the following array:

['text1', 'text2', 'text3', 'text4']
Merijndk
  • 1,674
  • 3
  • 18
  • 35
  • but you are ignoring the first array – Julio Popócatl May 06 '20 at 17:18
  • 1
    I don't think this deserves a downvote, as the example in your question is unclear. The case you provided will work just fine with `array_values()`. Next time, provide a more comprehensive example. – shevron May 07 '20 at 05:43