1

I have two strings. One is "Aa ee Gg", the other is "Aa Ee". Both are genetics for coat-color.

I wanted to generate a new combination out of both. The new string needs to have "one of the letters" of each string.

For example A and A, E and e, G and (-)

I tried to put the strings in arrays and then use these to make a new string.

Wild Widow
  • 2,359
  • 3
  • 22
  • 34
Anja
  • 13
  • 3
  • Show me the array that you want to produce in code format... – MaggsWeb Aug 15 '15 at 19:51
  • Aa ee Gg x Aa Ee can have many solutions. In my example it would be "AA Ee G-" but it also can be "aa Ee -g" always one "Letter" from String1 and one Letter from String2. So one A and one E and one G and so on ... – Anja Aug 15 '15 at 19:54
  • Why `AA Ee G-` and not `AA eE G-`? The latter seems to make more sense to me. – Darragh Enright Aug 15 '15 at 19:57
  • Or do you want to create a matrix of all possible solutions? – Darragh Enright Aug 15 '15 at 19:58
  • 1
    AA Ee G- or AA eE G- would give the same color. So of course it can be written like that. I am just used to sort from big to small letters :) Sorry if that was confusing. Of course from String1 there can only come an e not an E! Thank you. – Anja Aug 15 '15 at 19:59
  • @Darragh all possible solutions might be nice as well. Of course. I already would be happy if I can show one solution haha :D But yeah. All solutions would make my day! :D – Anja Aug 15 '15 at 20:01
  • Ah I just saw your update. I'll see if I can update my answer. – Darragh Enright Aug 15 '15 at 20:14

1 Answers1

0

This is probably a slightly obscure solution but it gives you the result you are looking for:

$first  = 'Aa ee Gg';
$second = 'Aa Ee';

$tokens = array_map(function($a, $b) {
    return ($a[0] ?: '-') . ($b[0] ?: '-');
}, explode(' ', $first), explode(' ', $second));

$string = implode(' ', $tokens);

var_dump($string);

This yields:

string(8) "AA eE G-"

A quick explanation:

  1. You start with the two strings $first and $second with the values you want to combine.
  2. Explode each string on whitespace to create two arrays, ['Aa', 'ee', 'Gg'] and ['Aa', 'Ee'] respectively.
  3. Use array_map() to apply a callback to each element of the two arrays
  4. In PHP it is possible to use array dereferencing syntax ($arr[0]) to dereference characters in strings. Here we're using a couple of shortcut ternary operators to return the first character in the current string, or return '-' if no character is present.
  5. array_map() returns an array of strings, in this case ['AA', 'eE', 'Gg'].
  6. Finally, implode() the array into the string "AA eE G-"

Hope this helps :)

Community
  • 1
  • 1
Darragh Enright
  • 13,676
  • 7
  • 41
  • 48