Skip to content

Instantly share code, notes, and snippets.

@RazaChohan
Created June 3, 2020 14:03
Show Gist options
  • Save RazaChohan/dd00a2c63644d520537508a8c10e9c69 to your computer and use it in GitHub Desktop.
Save RazaChohan/dd00a2c63644d520537508a8c10e9c69 to your computer and use it in GitHub Desktop.
Find intersection of array
$arr1 = ['a', 'b', 'c'];
$arr2 = ['b', 'c', 'd'];
$intersectionArray = [];
foreach($arr2 as $key => $char) {
$arr2[$char] = $char;
unset($arr2[$key]);
}
foreach($arr1 as $char) {
if(isset($arr2[$char])) {
$intersectionArray[] = $char;
}
}
echo implode(',', $intersectionArray);
//apple ale
//apple ael
function find($haystack, $needle) : bool {
$arrayStr = str_split($haystack);
$arrayNeedle = str_split($needle);
$needleIndex = 0;
$needleSize = count($arrayNeedle);
$isFound = true;
foreach($arrayStr as $char) {
if($needleIndex == $needleSize) {
break;
} else if ($char == $arrayNeedle[$needleIndex]) {
$needleIndex++;
}
}
$isFound = $needleIndex == $needleSize;
return $isFound;
}
echo (find('apple', 'ale') ? 'true' : 'false');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment