Saturday, September 5, 2015

manual dictionary function in php

<?php
function lowerCase($string){
    $new_string = "";
    $length = strlen($string);
    for($i = 0; $i < $length; $i++){
        if(ord($string[$i]) >= 65 && ord($string[$i]) <= 91){
            $new_string .= chr(ord($string[$i]) + 32);
        }else{
            $new_string .= $string[$i];
        }
    }
    return $new_string;
}

function which_is_first($string1, $string2){
    $string1 = lowerCase($string1);
    $string2 = lowerCase($string2);
    $len1 = strlen($string1);
    $len2 = strlen($string2);
    if($len1 < $len2){
        $min_len = $len1;
    }else{
        $min_len = $len2;
    }
    for($i = 0; $i < $min_len; $i++){
        if($string1[$i] > $string2[$i]){
            return 2;
        }elseif($string1[$i] < $string2[$i]){
            return 1;
        }
    }
    if($len1 < $len2){
        return 1;
    }else{
        return 2;
    }

}
function dictionary($words){
    $arr_len = count($words);
    for($i = 0; $i < $arr_len; $i++){
        for($k = $i; $k < $arr_len; $k++){
            if(which_is_first($words[$i], $words[$k]) == 2 ){
                $temp = $words[$i];
                $words[$i] = $words[$k];
                $words[$k] = $temp;
            }
        }
    }
    return $words;
}
$dictionary = dictionary(['cat', 'bat', 'ball', 'home', 'he', 'she']);
print_r($dictionary);

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }