phparraysfilteringprefixarray-intersect

Filter flat array where leading integer is found in another flat array


I need to intersect two arrays where the leading number of a given value is found in another array.

$A = [
    '104-20_140.1',
    '104-10_136.1',
    '104-40_121.1',
    '104-41_122.1',
    '200-42_951.1',
    '200-43_952.1',
    '200-44_123.1',
    '200-45_124.1',
    '300-46_125.1',
    '300-47_126.1', 
    '300-48_127.1',
    '300-49_128.1',
    '380-56_125.1',
    '380-57_126.1',
    '380-58_127.1',
    '380-59_128.1',
];

$B = ['200', '300'];

I need two look at Array A's beginning of the value. Ex. [0] => 104-20_140 and see if the beginning '104' it exists in Array B. If not Array A shall remove it from the result array C.

The output with Array A and B should have:

[
     '200-42_951.1',
     '200-43_952.1',
     '200-44_123.1',
     '200-45_124.1',
     '300-46_125.1',
     '300-47_126.1',
     '300-48_127.1',
     '300-49_128.1',
]

Solution

  • Try this:

    function startsWith($haystack, $needle) {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
    
    $C = array();
    foreach ($A as $ka => $va) {
        foreach ($B as $kb => $vb) {
            if (startsWith($va, $vb)) {
                $C[] = $va;
            }
        }
    }
    

    example on codepad