Why you must know associate arrays in PHP

Associative arrays can be used to create a link between two related items into a key-value pair.

Example Problem: https://www.codechef.com/problems/TOTR

Problem description: Given a string that represents the equivalent of the English alphabets, print the English equivalent of other strings based on that string.

Solution code:

<?php

$t = readline();

$input = explode(' ', $t);

$a = array();
$to_translate = strtolower($input[1]);
for($i = 0; $i < strlen($to_translate); $i++) {
    array_push($a, $a[chr(97 + $i)] = $to_translate[$i]);
}

for($i = 0; $i < strlen($to_translate); $i++) {
    array_push($a, $a[chr(65 + $i)] = strtoupper($to_translate[$i]));
}

array_push($a, $a['?'] = '?');
array_push($a, $a['_'] = ' ');
array_push($a, $a['.'] = '.');
array_push($a, $a[','] = ',');
array_push($a, $a['!'] = '!');

for($j = 0; $j < $input[0]; $j++) {
    $string = readline();
    
    $output = '';
    for($k = 0; $k < strlen($string); $k++) {
        if(array_key_exists($string[$k], $a)) {
            $output .= $a[$string[$k]];
        }
    }
    print($output . PHP_EOL);
}        

要查看或添加评论,请登录

Vijay Kumar的更多文章

社区洞察

其他会员也浏览了