3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array1 = ['Apple','Juice']; $array1_keys = ['Apple' => 1, 'Juice' => 1]; $array2 = ['Apple Juice', 'Apple', 'Red Apple', 'Juice', 'Pineapple', 'Apple Juice Apple']; $result = []; array_walk($array2, function($val, $key) use (&$result, $array1_keys) { $words = explode(' ', $val); $wordcounts = array_count_values($words); $result[$val] = array_sum(array_intersect_key($wordcounts, $array1_keys)); } ); var_dump($result);
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
array(6) { ["Apple Juice"]=> int(2) ["Apple"]=> int(1) ["Red Apple"]=> int(1) ["Juice"]=> int(1) ["Pineapple"]=> int(0) ["Apple Juice Apple"]=> int(3) }

preferences:
101.47 ms | 1530 KiB | 4 Q