1

I have two arrays:

$array1 = [29, 'a', 'x', 'c', 11];
$array2 = ['a' => 20, 'x' => 21, 'c' => 23];

I want to get an array that looks like:

$array3 = [29, 20, 21, 23, 11];

I know how to do it with a foreach loop, but I was wondering if there was a way to do it as a one liner, or maybe with some sort of anonymous function.

4
  • 3
    array_walk($array1, function(&$value) use ($array2) { $value = isset($array2[$value]) ? $array2[$value] : $value; } ); or array_walk($array1, function(&$value) use ($array2) { $value = $array2[$value] ?? $value; } ); for PHP>7.0 Commented Sep 25, 2017 at 15:26
  • @MarkBaker yep, that's pretty good. cheers. I like the php7! if you post as an answer I will accept it Commented Sep 25, 2017 at 15:30
  • Did you give up? Commented Sep 29, 2017 at 17:47
  • No, I used the comment by @MarkBaker, array_walk($array1, function(&$value) use ($array2) { $value = $array2[$value] ?? $value; } ) Commented Oct 3, 2017 at 2:01

5 Answers 5

2

array_map work as well the other answer :

$array1 = [29, 1=>'a', 2=>'x',3=>'c', 11];
$array2 = ['a'=>20, 'x'=>21, 'c'=>23];

$array3 = array_map(function($a) use($array2){return is_int($a) ? $a : $array2[$a];}, $array1);
Sign up to request clarification or add additional context in comments.

Comments

2

You can add them and filter out non-numeric values:

$array3 = array_values(array_filter($array1 + $array2, 'is_numeric'));

If the order is important:

$array3 = array_filter(call_user_func_array(
                       'array_merge', array_map(null, $array1, $array2)), 
                       'is_numeric');

Then array_values if you need to re-index.

In either case, if you want only integers or floats then use is_int or is_float.

1 Comment

yep, I would like to remove the keys I don't need
1

An attempt with a one-liner :

$array1 = [29, 1=>'a', 2=>'x',3=>'c', 11];
$array2 = ['a'=>20, 'x'=>21, 'c'=>23];

$array3 = array_values(array_filter(array_merge($array1,$array2),function($i){return is_int($i);}));

print_r($array3);

// Outputs :
/*
Array
(
    [0] => 29
    [1] => 11
    [2] => 20
    [3] => 21
    [4] => 23
)
*/

Comments

0

I reckon this looks more elegant than the earlier posted solutions...

Code: (Demo)

var_export(
    array_map(fn($v) => $array2[$v] ?? $v, $array1)
);

Attempt to access the mapping array's value by key; if there is no matching key, then default to the original value.

Comments

-1

If you don't like to use foreach() you can use array_replace() function. You can learn more about this function in below:

Array_replace($array1 , $array2, $...) in php.net

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.