Created
June 3, 2020 14:03
-
-
Save RazaChohan/dd00a2c63644d520537508a8c10e9c69 to your computer and use it in GitHub Desktop.
Find intersection of array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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