Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How correctly to process an arrays?

Tags:

arrays

php

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?

like image 613
morepusto Avatar asked Aug 07 '18 20:08

morepusto


Video Answer


2 Answers

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

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);
like image 188
aefxx Avatar answered Oct 16 '22 00:10

aefxx


Surprisingly, this one was quite fun to execute. Since you went very specific on end of the element, I decided to use RegEx for that.

Here is my approach:

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

foreach ($arr2 as $find) {
   foreach ($arr1 as $key => $element) {
        $arr1[$key] = preg_replace('/' . $find . '$/', '_' . $find, $element);
    }
}

For every element of the second array (since they are not repeated), I go through every element of the first array and check if the value can be found at the end of the element of the second array using the $ anchor from RegEx which forces it to look it from the end of the string.

This way the $arr1 will have exactly what you expect.

[Edit] Following the scape suggestion from @aefxx and improving variable names.

like image 37
Rafael Avatar answered Oct 15 '22 22:10

Rafael