<?php

function get_index($word) {
    
$index = array();
    for (
$i 0$lenght strlen($word); $i $lenght$i++) {
        @
$index[$word[$i]]++;
    }
    
ksort($index);
    return 
$index;
}

function 
get_diff($count1$count2) {
    return 
$count2 $count1;
}

function 
compose_words($word$dictionary) {
    
$index get_index($word); $length strlen($word);
    if (
$fp fopen($dictionary'r')) {
        while (!
feof($fp)) {
            
$current_word trim(fgets($fp));
            
$current_length strlen($current_word);
            if (
$current_length && $current_length <= $length) {
                
$current_index get_index($current_word);
                if (
array_keys($current_index) == array_keys(array_intersect_key($current_index$index))
                    && 
min(array_map('get_diff'$current_index$index)) >= 0) {
                    echo 
$current_word PHP_EOL;
                }
            }
        }
        
fclose($fp);
    }
}

compose_words('мегаполис''dictionary.txt');