# How correctly to process an arrays?

• A+
Category：Languages

There are two arrays:

``\$arr1 = ['word', 'tech', 'care', 'kek', 'lol', 'wild', 'regex']; \$arr2 = ['ord', 'ek', 'ol', 'ld', 'gex', 'ss']; ``

The number of elements in the second array is less than or equal to the first array.

Sort out the first array and the second array, if the elements of the second array are contained at the end of the elements of the first array, sort the array in this form:

``Array (     [0] => w_ord     [1] => tech     [2] => care     [3] => k_ek     [4] => l_ol     [5] => wi_ld     [6] => re_gex ) ``

Important: the elements of the second array are never repeated, and can go in any order. If in the second element there is no end of the element of the first array, then set the value of the element of the first array.

I do this:

``foreach(\$arr2 as \$val) {     \$strrepl[\$val] = "_".\$val; }  foreach(\$arr1 as \$key => \$val) {     \$arr3[\$key] = str_replace(array_keys(\$strrepl), \$strrepl, \$val); }  print_r(\$arr3); ``

But I'm not sure that this is the right approach, what will you advise?

Hmm, let's see ... purely functional 'cause you know

``function ends(\$str) {   return function(\$suffix) use(\$str) {     return mb_strlen(\$str) >= mb_strlen(\$suffix)       && mb_substr(\$str, mb_strlen(\$suffix) * -1) === \$suffix;   }; }  \$result = array_map(function(\$item) use(\$arr2) {   \$filter = ends(\$item);   \$suffixes = array_filter(\$arr2, \$filter);    if (empty(\$suffixes)) {     return \$item;   }   // This only cares about the very first match, but   // is easily adaptable to handle all of them   \$suffix = reset(\$suffixes);    return mb_substr(\$item, 0, mb_strlen(\$suffix) * -1) . "_{\$suffix}"; }, \$arr1); ``