PHP Interview Question - String comparison

Check if the letters in the second string are present in the first string – PHP Problem

This is a PHP Interview Question.

Create a function that accepts an array of two strings and checks if the letters in the second string are present in the first string.

Examples

stringCheck([“trances”, “nectar”]) ➞ true
stringCheck([“compadres”, “DRAPES”]) ➞ true
stringCheck([“parses”, “parsecs”]) ➞ false

Solution

<!DOCTYPE html>
<html>
<body>
<?php
function stringCheck ($txt1, $txt2){
$result = "true";

//creating array of txt2 characters
$arr = str_split($txt2);

foreach ($arr as $a)
{
//check each character of string to present in string 1
   if(strpos($txt1, $a)===FALSE){
      $result = "false"; //character not present
   }
}
echo $result;
}
stringCheck ("trances", "nectar");
stringCheck ("compadres", "DRAPES");
stringCheck ("parses", "parsecs");
?>

</body>
</html>

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.