Search code examples
phparraysstringcpu-wordletter

Check if a word can be created from a random letter string using PHP


<?php
    $randomstring = 'raabccdegep';
    $arraylist = array("car", "egg", "total");
?>

Above $randomstring is a string which contain some alphabet letters. And I Have an Array called $arraylist which Contain 3 Words Such as 'car' , 'egg' , 'total'.

Now I need to check the string Using the words in array and print if the word can be created using the string. For Example I need an Output Like.

car is possible.
egg is not possible.
total is not possible.

Also Please Check the repetition of letter. ie, beep is also possible. Because the string contains two e. But egg is not possible because there is only one g.


Solution

  • function find_in( $haystack, $item ) {
        $match = '';
        foreach( str_split( $item ) as $char ) {
            if ( strpos( $haystack, $char ) !== false ) {
                $haystack = substr_replace( $haystack, '', strpos( $haystack, $char ), 1 );
                $match .= $char;
            }
        }
        return $match === $item;
    }
    
    $randomstring = 'raabccdegep';
    $arraylist = array( "beep", "car", "egg", "total");
    
    foreach ( $arraylist as $item ) {
        echo find_in( $randomstring, $item ) ? " $item found in $randomstring." : " $item not found in $randomstring.";
    }