Search code examples
phparraysloopsstr-replacestrpos

PHP: combine arrays using strpos and str_replace


I have 2 arrays, that look like this:

$alertTypes = ['outbid', 'subAllVendorComments'];

$channels = ['outbiduseSms', 'outbiduseBrowser', 'subAllVendorCommentsuseEmail', 'subAllVendorCommentsuseWhatsApp'];

My aim is to combine them into one array that is structured like this:

Array
(
    [outbid] => Array
        (
            [0] => useSms,
            [1] => useBrowser
        )

    [subAllVendorComments] => Array
        (
            [0] => useEmail,
            [1] => useWhatsApp
        )
)

The elements in each sub-array are the words in the $channels array that begin with the word in the $alertTypes array.

I have tried the following, but it doesn't work as it relies on there only being one element in the $channels array that begins with the same word in the $alertTypes array:

$result = [];

for($i = 0; $i < count($alertTypes); $i++) {
    if(strpos($channels[$i], $alertTypes[$i]) !== false) {
        $result[$alertTypes[$i]] = [str_replace($alertTypes[$i], '', $channels[$i])];
    }
}

Any help is appreciated.


Solution

  • You're using the same index $i for both arrays, which will only work when the string in $alertTypes is in the corresponding element of $channels. You need to compare the alert types with all channels, which can be done using nested loops.

    You're also replacing the element of $result instead of pushing onto the nested array.

    The code will also be easier if you use foreach instead of for.

    foreach ($alertTypes as $alert) {
        $array = [];
        foreach ($channels as $channel) {
            if (strpos($channel, $alert) !== false) {
                $array[] = str_replace($alert, '', $channel);
            }
        }
        $result[$alert] = $array;
    }