edgarmtze
edgarmtze

Reputation: 25048

Search associative array and print corresponding value in php

I have a dictionary like

UUU F
UUC F
CUU L
CUC L
UUA L
CUA L
UUG L
CUG L
AUU I
AUC I
AUA I
GUU V
GUC V
GUG V
GUA V

So Given a string I want to replace every 3 chars its respective char

I was thinking on using associative arrays:

    $d = array();
$d['UUU']='F';
$d['UUC']='F';
$d['UUA']='L';
$d['CUU']='L';
$d['GUC']='V';
$d['GUG']='V';
$d['GUA']='V';
$d['UUG']='L';
$d['CUG']='L';

$s = "UUAGUAUUG";
$temp="";
for($i=0; $i<strlen($s)+1; $i++){ 
    $temp .= $s[$i];
    if($i%3==0){
        echo $temp;
        echo array_search($temp, $d);
        $temp = "";
    }   
}



It should output LVL but have no success

Upvotes: 1

Views: 349

Answers (5)

Matthew
Matthew

Reputation: 48294

The basic solution is:

<?php
$dict = array(
 'UUU' => 'F',
 'UUC' => 'F',
 'UUA' => 'L',
 'CUU' => 'L',
 'GUC' => 'V',
 'GUG' => 'V',
 'GUA' => 'V',
 'UUG' => 'L',
 'CUG' => 'L'
);

$before = "UUAGUAUUG";

$after = strtr($before, $dict);

Although you may be able to write a faster version that takes into account that you are replacing every three letters.

And I'm not 100% sure this will even work, given what kind of combinations can overlap over the 3-char barrier. Which leaves you with this rotten solution:

$after = str_replace('-', '',
  strtr(preg_replace('/[A-Z]{3}/', '\0-', $before), $dict));

Seriously, don't try this at home. ;)

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

I think this might work:

$temp = implode(array_map(function($a) { return $d[$a];}, str_split($s, 3)));

Upvotes: 1

SalGad
SalGad

Reputation: 3011

Change your for loop to this:

for($i=0; $i<strlen($s)+1; $i++){ 
    $temp .= $s[$i];
    if(($i+1)%3==0){
        echo $d[$temp];
        $temp = "";
    }   
}

Your i value starts from 0. And array_values does not give the expected answer.

Upvotes: 0

Ast Derek
Ast Derek

Reputation: 2729

Use str_split:

$s = 'UUAGUAUUG';
$split = str_split($s,3);
$translated = array();

foreach ($split as $bases) {
    /**
     * @ supresses warnings if the array index doesn't exist
     */
    $translated []= @$d[$bases];
}

echo join('',$translated);

Upvotes: 2

paddy
paddy

Reputation: 63481

You're testing at the wrong time.

Change $i%3 == 0 to $i%3 == 2.

The reason here is that you have added to your temporary string first. That means you immediately check a string of length 1 ("U") and then clear it. Then you go around for another 3 times and you get "UAG", followed by "UAU". Neither of these are in your array.

What I don't understand is that you output the value of $temp each time this happens, so you should have picked up on this.

Upvotes: 0

Related Questions